1 package de.juplo.kafka;
3 import lombok.extern.slf4j.Slf4j;
4 import org.apache.kafka.clients.consumer.ConsumerRecord;
5 import org.apache.kafka.clients.consumer.KafkaConsumer;
6 import org.apache.kafka.clients.producer.KafkaProducer;
7 import org.apache.kafka.clients.producer.ProducerRecord;
8 import org.apache.kafka.common.TopicPartition;
9 import org.apache.kafka.common.errors.RecordDeserializationException;
10 import org.apache.kafka.common.serialization.*;
11 import org.apache.kafka.common.utils.Bytes;
12 import org.junit.jupiter.api.*;
13 import org.springframework.beans.factory.annotation.Autowired;
14 import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
15 import org.springframework.boot.test.context.ConfigDataApplicationContextInitializer;
16 import org.springframework.boot.test.context.TestConfiguration;
17 import org.springframework.context.annotation.Bean;
18 import org.springframework.context.annotation.Import;
19 import org.springframework.kafka.test.context.EmbeddedKafka;
20 import org.springframework.test.context.TestPropertySource;
21 import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
23 import java.time.Duration;
25 import java.util.concurrent.ExecutionException;
26 import java.util.concurrent.ExecutorService;
27 import java.util.function.BiConsumer;
28 import java.util.stream.Collectors;
29 import java.util.stream.IntStream;
31 import static de.juplo.kafka.ApplicationTests.PARTITIONS;
32 import static de.juplo.kafka.ApplicationTests.TOPIC;
33 import static org.assertj.core.api.Assertions.*;
34 import static org.awaitility.Awaitility.*;
37 @SpringJUnitConfig(initializers = ConfigDataApplicationContextInitializer.class)
38 @TestMethodOrder(MethodOrderer.OrderAnnotation.class)
41 "consumer.bootstrap-server=${spring.embedded.kafka.brokers}",
42 "consumer.topic=" + TOPIC,
43 "consumer.commit-interval=1s" })
44 @EmbeddedKafka(topics = TOPIC, partitions = PARTITIONS)
45 @EnableAutoConfiguration
47 class ApplicationTests
49 public static final String TOPIC = "FOO";
50 public static final int PARTITIONS = 10;
53 StringSerializer stringSerializer = new StringSerializer();
56 Serializer valueSerializer;
58 KafkaProducer<String, Bytes> kafkaProducer;
60 KafkaConsumer<String, Long> kafkaConsumer;
62 KafkaConsumer<Bytes, Bytes> offsetConsumer;
64 ApplicationProperties properties;
66 ExecutorService executor;
68 KeyCountingRecordHandler keyCountingRecordHandler;
70 EndlessConsumer<String, Long> endlessConsumer;
71 Map<TopicPartition, Long> oldOffsets;
72 Map<TopicPartition, Long> newOffsets;
73 Set<ConsumerRecord<String, Long>> receivedRecords;
79 void commitsCurrentOffsetsOnSuccess() throws ExecutionException, InterruptedException
81 send100Messages((partition, key, counter) ->
83 Bytes value = new Bytes(valueSerializer.serialize(TOPIC, counter));
84 return new ProducerRecord<>(TOPIC, partition, key, value);
87 await("100 records received")
88 .atMost(Duration.ofSeconds(30))
89 .pollInterval(Duration.ofSeconds(1))
90 .until(() -> receivedRecords.size() >= 100);
92 await("Offsets committed")
93 .atMost(Duration.ofSeconds(10))
94 .pollInterval(Duration.ofSeconds(1))
97 checkSeenOffsetsForProgress();
98 compareToCommitedOffsets(newOffsets);
101 assertThatExceptionOfType(IllegalStateException.class)
102 .isThrownBy(() -> endlessConsumer.exitStatus())
103 .describedAs("Consumer should still be running");
107 void commitsOffsetOfErrorForReprocessingOnDeserializationError()
109 send100Messages((partition, key, counter) ->
111 Bytes value = counter == 77
112 ? new Bytes(stringSerializer.serialize(TOPIC, "BOOM!"))
113 : new Bytes(valueSerializer.serialize(TOPIC, counter));
114 return new ProducerRecord<>(TOPIC, partition, key, value);
117 await("Consumer failed")
118 .atMost(Duration.ofSeconds(30))
119 .pollInterval(Duration.ofSeconds(1))
120 .until(() -> !endlessConsumer.running());
122 checkSeenOffsetsForProgress();
123 compareToCommitedOffsets(newOffsets);
125 endlessConsumer.start();
126 await("Consumer failed")
127 .atMost(Duration.ofSeconds(30))
128 .pollInterval(Duration.ofSeconds(1))
129 .until(() -> !endlessConsumer.running());
131 checkSeenOffsetsForProgress();
132 compareToCommitedOffsets(newOffsets);
133 assertThat(receivedRecords.size())
134 .describedAs("Received not all sent events")
137 assertThatNoException()
138 .describedAs("Consumer should not be running")
139 .isThrownBy(() -> endlessConsumer.exitStatus());
140 assertThat(endlessConsumer.exitStatus())
141 .describedAs("Consumer should have exited abnormally")
142 .containsInstanceOf(RecordDeserializationException.class);
146 /** Helper methods for the verification of expectations */
148 void compareToCommitedOffsets(Map<TopicPartition, Long> offsetsToCheck)
150 doForCurrentOffsets((tp, offset) ->
152 Long expected = offsetsToCheck.get(tp) + 1;
153 log.debug("Checking, if the offset for {} is {}", tp, expected);
155 .describedAs("Committed offset corresponds to the offset of the consumer")
156 .isEqualTo(expected);
160 void checkSeenOffsetsForProgress()
162 // Be sure, that some messages were consumed...!
163 Set<TopicPartition> withProgress = new HashSet<>();
164 partitions().forEach(tp ->
166 Long oldOffset = oldOffsets.get(tp) + 1;
167 Long newOffset = newOffsets.get(tp) + 1;
168 if (!oldOffset.equals(newOffset))
170 log.debug("Progress for {}: {} -> {}", tp, oldOffset, newOffset);
171 withProgress.add(tp);
174 assertThat(withProgress)
175 .describedAs("Some offsets must have changed, compared to the old offset-positions")
180 /** Helper methods for setting up and running the tests */
184 offsetConsumer.assign(partitions());
185 offsetConsumer.seekToEnd(partitions());
186 partitions().forEach(tp ->
188 // seekToEnd() works lazily: it only takes effect on poll()/position()
189 Long offset = offsetConsumer.position(tp);
190 log.info("New position for {}: {}", tp, offset);
192 // The new positions must be commited!
193 offsetConsumer.commitSync();
194 offsetConsumer.unsubscribe();
197 void doForCurrentOffsets(BiConsumer<TopicPartition, Long> consumer)
199 offsetConsumer.assign(partitions());
200 partitions().forEach(tp -> consumer.accept(tp, offsetConsumer.position(tp)));
201 offsetConsumer.unsubscribe();
204 List<TopicPartition> partitions()
208 .range(0, PARTITIONS)
209 .mapToObj(partition -> new TopicPartition(TOPIC, partition))
210 .collect(Collectors.toList());
214 public interface RecordGenerator<K, V>
216 public ProducerRecord<String, Bytes> generate(int partition, String key, long counter);
219 void send100Messages(RecordGenerator recordGenerator)
223 for (int partition = 0; partition < 10; partition++)
225 for (int key = 0; key < 10; key++)
227 ProducerRecord<String, Bytes> record =
228 recordGenerator.generate(partition, Integer.toString(partition*10+key%2), ++i);
230 kafkaProducer.send(record, (metadata, e) ->
232 if (metadata != null)
236 metadata.partition(),
244 "Exception for {}={}: {}",
260 oldOffsets = new HashMap<>();
261 newOffsets = new HashMap<>();
262 receivedRecords = new HashSet<>();
264 doForCurrentOffsets((tp, offset) ->
266 oldOffsets.put(tp, offset - 1);
267 newOffsets.put(tp, offset - 1);
270 TestRecordHandler<String, Long> captureOffsetAndExecuteTestHandler =
271 new TestRecordHandler<String, Long>(keyCountingRecordHandler) {
273 public void onNewRecord(ConsumerRecord<String, Long> record)
276 new TopicPartition(record.topic(), record.partition()),
278 receivedRecords.add(record);
283 new EndlessConsumer<>(
285 properties.getClientId(),
286 properties.getTopic(),
288 captureOffsetAndExecuteTestHandler);
290 endlessConsumer.start();
298 endlessConsumer.stop();
302 log.info("Exception while stopping the consumer: {}", e.toString());
308 @Import(ApplicationConfiguration.class)
309 public static class Configuration
312 Serializer<Long> serializer()
314 return new LongSerializer();
318 KafkaProducer<String, Bytes> kafkaProducer(ApplicationProperties properties)
320 Properties props = new Properties();
321 props.put("bootstrap.servers", properties.getBootstrapServer());
322 props.put("linger.ms", 100);
323 props.put("key.serializer", StringSerializer.class.getName());
324 props.put("value.serializer", BytesSerializer.class.getName());
326 return new KafkaProducer<>(props);
330 KafkaConsumer<Bytes, Bytes> offsetConsumer(ApplicationProperties properties)
332 Properties props = new Properties();
333 props.put("bootstrap.servers", properties.getBootstrapServer());
334 props.put("client.id", "OFFSET-CONSUMER");
335 props.put("group.id", properties.getGroupId());
336 props.put("key.deserializer", BytesDeserializer.class.getName());
337 props.put("value.deserializer", BytesDeserializer.class.getName());
339 return new KafkaConsumer<>(props);