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.autoconfigure.data.mongo.AutoConfigureDataMongo;
16 import org.springframework.boot.test.context.ConfigDataApplicationContextInitializer;
17 import org.springframework.boot.test.context.TestConfiguration;
18 import org.springframework.context.annotation.Bean;
19 import org.springframework.context.annotation.Import;
20 import org.springframework.kafka.test.context.EmbeddedKafka;
21 import org.springframework.test.context.TestPropertySource;
22 import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
24 import java.time.Duration;
26 import java.util.concurrent.ExecutionException;
27 import java.util.concurrent.ExecutorService;
28 import java.util.function.BiConsumer;
29 import java.util.stream.Collectors;
30 import java.util.stream.IntStream;
32 import static de.juplo.kafka.ApplicationTests.PARTITIONS;
33 import static de.juplo.kafka.ApplicationTests.TOPIC;
34 import static org.assertj.core.api.Assertions.*;
35 import static org.awaitility.Awaitility.*;
38 @SpringJUnitConfig(initializers = ConfigDataApplicationContextInitializer.class)
39 @TestMethodOrder(MethodOrderer.OrderAnnotation.class)
42 "consumer.bootstrap-server=${spring.embedded.kafka.brokers}",
43 "consumer.topic=" + TOPIC,
44 "consumer.commit-interval=1s",
45 "spring.mongodb.embedded.version=4.4.13" })
46 @EmbeddedKafka(topics = TOPIC, partitions = PARTITIONS)
47 @EnableAutoConfiguration
48 @AutoConfigureDataMongo
50 class ApplicationTests
52 public static final String TOPIC = "FOO";
53 public static final int PARTITIONS = 10;
56 StringSerializer stringSerializer = new StringSerializer();
59 Serializer valueSerializer;
61 KafkaProducer<String, Bytes> kafkaProducer;
63 KafkaConsumer<String, Long> kafkaConsumer;
65 KafkaConsumer<Bytes, Bytes> offsetConsumer;
67 ApplicationProperties properties;
69 ExecutorService executor;
71 KeyCountingRebalanceListener keyCountingRebalanceListener;
73 KeyCountingRecordHandler keyCountingRecordHandler;
75 EndlessConsumer<String, Long> endlessConsumer;
76 Map<TopicPartition, Long> oldOffsets;
77 Map<TopicPartition, Long> newOffsets;
78 Set<ConsumerRecord<String, Long>> receivedRecords;
84 void commitsCurrentOffsetsOnSuccess() throws ExecutionException, InterruptedException
86 send100Messages((partition, key, counter) ->
88 Bytes value = new Bytes(valueSerializer.serialize(TOPIC, counter));
89 return new ProducerRecord<>(TOPIC, partition, key, value);
92 await("100 records received")
93 .atMost(Duration.ofSeconds(30))
94 .pollInterval(Duration.ofSeconds(1))
95 .until(() -> receivedRecords.size() >= 100);
97 await("Offsets committed")
98 .atMost(Duration.ofSeconds(10))
99 .pollInterval(Duration.ofSeconds(1))
102 checkSeenOffsetsForProgress();
103 compareToCommitedOffsets(newOffsets);
106 assertThatExceptionOfType(IllegalStateException.class)
107 .isThrownBy(() -> endlessConsumer.exitStatus())
108 .describedAs("Consumer should still be running");
112 void commitsOffsetOfErrorForReprocessingOnDeserializationError()
114 send100Messages((partition, key, counter) ->
116 Bytes value = counter == 77
117 ? new Bytes(stringSerializer.serialize(TOPIC, "BOOM!"))
118 : new Bytes(valueSerializer.serialize(TOPIC, counter));
119 return new ProducerRecord<>(TOPIC, partition, key, value);
122 await("Consumer failed")
123 .atMost(Duration.ofSeconds(30))
124 .pollInterval(Duration.ofSeconds(1))
125 .until(() -> !endlessConsumer.running());
127 checkSeenOffsetsForProgress();
128 compareToCommitedOffsets(newOffsets);
130 endlessConsumer.start();
131 await("Consumer failed")
132 .atMost(Duration.ofSeconds(30))
133 .pollInterval(Duration.ofSeconds(1))
134 .until(() -> !endlessConsumer.running());
136 checkSeenOffsetsForProgress();
137 compareToCommitedOffsets(newOffsets);
138 assertThat(receivedRecords.size())
139 .describedAs("Received not all sent events")
142 assertThatNoException()
143 .describedAs("Consumer should not be running")
144 .isThrownBy(() -> endlessConsumer.exitStatus());
145 assertThat(endlessConsumer.exitStatus())
146 .describedAs("Consumer should have exited abnormally")
147 .containsInstanceOf(RecordDeserializationException.class);
151 /** Helper methods for the verification of expectations */
153 void compareToCommitedOffsets(Map<TopicPartition, Long> offsetsToCheck)
155 doForCurrentOffsets((tp, offset) ->
157 Long expected = offsetsToCheck.get(tp) + 1;
158 log.debug("Checking, if the offset for {} is {}", tp, expected);
160 .describedAs("Committed offset corresponds to the offset of the consumer")
161 .isEqualTo(expected);
165 void checkSeenOffsetsForProgress()
167 // Be sure, that some messages were consumed...!
168 Set<TopicPartition> withProgress = new HashSet<>();
169 partitions().forEach(tp ->
171 Long oldOffset = oldOffsets.get(tp) + 1;
172 Long newOffset = newOffsets.get(tp) + 1;
173 if (!oldOffset.equals(newOffset))
175 log.debug("Progress for {}: {} -> {}", tp, oldOffset, newOffset);
176 withProgress.add(tp);
179 assertThat(withProgress)
180 .describedAs("Some offsets must have changed, compared to the old offset-positions")
185 /** Helper methods for setting up and running the tests */
189 offsetConsumer.assign(partitions());
190 offsetConsumer.seekToEnd(partitions());
191 partitions().forEach(tp ->
193 // seekToEnd() works lazily: it only takes effect on poll()/position()
194 Long offset = offsetConsumer.position(tp);
195 log.info("New position for {}: {}", tp, offset);
197 // The new positions must be commited!
198 offsetConsumer.commitSync();
199 offsetConsumer.unsubscribe();
202 void doForCurrentOffsets(BiConsumer<TopicPartition, Long> consumer)
204 offsetConsumer.assign(partitions());
205 partitions().forEach(tp -> consumer.accept(tp, offsetConsumer.position(tp)));
206 offsetConsumer.unsubscribe();
209 List<TopicPartition> partitions()
213 .range(0, PARTITIONS)
214 .mapToObj(partition -> new TopicPartition(TOPIC, partition))
215 .collect(Collectors.toList());
219 public interface RecordGenerator<K, V>
221 public ProducerRecord<String, Bytes> generate(int partition, String key, long counter);
224 void send100Messages(RecordGenerator recordGenerator)
228 for (int partition = 0; partition < 10; partition++)
230 for (int key = 0; key < 10; key++)
232 ProducerRecord<String, Bytes> record =
233 recordGenerator.generate(partition, Integer.toString(partition*10+key%2), ++i);
235 kafkaProducer.send(record, (metadata, e) ->
237 if (metadata != null)
241 metadata.partition(),
249 "Exception for {}={}: {}",
265 oldOffsets = new HashMap<>();
266 newOffsets = new HashMap<>();
267 receivedRecords = new HashSet<>();
269 doForCurrentOffsets((tp, offset) ->
271 oldOffsets.put(tp, offset - 1);
272 newOffsets.put(tp, offset - 1);
275 TestRecordHandler<String, Long> captureOffsetAndExecuteTestHandler =
276 new TestRecordHandler<String, Long>(keyCountingRecordHandler) {
278 public void onNewRecord(ConsumerRecord<String, Long> record)
281 new TopicPartition(record.topic(), record.partition()),
283 receivedRecords.add(record);
288 new EndlessConsumer<>(
290 properties.getClientId(),
291 properties.getTopic(),
293 keyCountingRebalanceListener,
294 captureOffsetAndExecuteTestHandler);
296 endlessConsumer.start();
304 endlessConsumer.stop();
308 log.info("Exception while stopping the consumer: {}", e.toString());
314 @Import(ApplicationConfiguration.class)
315 public static class Configuration
318 Serializer<Long> serializer()
320 return new LongSerializer();
324 KafkaProducer<String, Bytes> kafkaProducer(ApplicationProperties properties)
326 Properties props = new Properties();
327 props.put("bootstrap.servers", properties.getBootstrapServer());
328 props.put("linger.ms", 100);
329 props.put("key.serializer", StringSerializer.class.getName());
330 props.put("value.serializer", BytesSerializer.class.getName());
332 return new KafkaProducer<>(props);
336 KafkaConsumer<Bytes, Bytes> offsetConsumer(ApplicationProperties properties)
338 Properties props = new Properties();
339 props.put("bootstrap.servers", properties.getBootstrapServer());
340 props.put("client.id", "OFFSET-CONSUMER");
341 props.put("group.id", properties.getGroupId());
342 props.put("key.deserializer", BytesDeserializer.class.getName());
343 props.put("value.deserializer", BytesDeserializer.class.getName());
345 return new KafkaConsumer<>(props);