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 KeyCountingRebalanceListener keyCountingRebalanceListener;
70 KeyCountingRecordHandler keyCountingRecordHandler;
72 EndlessConsumer<String, Long> endlessConsumer;
73 Map<TopicPartition, Long> oldOffsets;
74 Map<TopicPartition, Long> newOffsets;
75 Set<ConsumerRecord<String, Long>> receivedRecords;
81 void commitsCurrentOffsetsOnSuccess() throws ExecutionException, InterruptedException
83 send100Messages((partition, key, counter) ->
85 Bytes value = new Bytes(valueSerializer.serialize(TOPIC, counter));
86 return new ProducerRecord<>(TOPIC, partition, key, value);
89 await("100 records received")
90 .atMost(Duration.ofSeconds(30))
91 .pollInterval(Duration.ofSeconds(1))
92 .until(() -> receivedRecords.size() >= 100);
94 await("Offsets committed")
95 .atMost(Duration.ofSeconds(10))
96 .pollInterval(Duration.ofSeconds(1))
99 checkSeenOffsetsForProgress();
100 compareToCommitedOffsets(newOffsets);
103 assertThatExceptionOfType(IllegalStateException.class)
104 .isThrownBy(() -> endlessConsumer.exitStatus())
105 .describedAs("Consumer should still be running");
109 void commitsOffsetOfErrorForReprocessingOnDeserializationError()
111 send100Messages((partition, key, counter) ->
113 Bytes value = counter == 77
114 ? new Bytes(stringSerializer.serialize(TOPIC, "BOOM!"))
115 : new Bytes(valueSerializer.serialize(TOPIC, counter));
116 return new ProducerRecord<>(TOPIC, partition, key, value);
119 await("Consumer failed")
120 .atMost(Duration.ofSeconds(30))
121 .pollInterval(Duration.ofSeconds(1))
122 .until(() -> !endlessConsumer.running());
124 checkSeenOffsetsForProgress();
125 compareToCommitedOffsets(newOffsets);
127 endlessConsumer.start();
128 await("Consumer failed")
129 .atMost(Duration.ofSeconds(30))
130 .pollInterval(Duration.ofSeconds(1))
131 .until(() -> !endlessConsumer.running());
133 checkSeenOffsetsForProgress();
134 compareToCommitedOffsets(newOffsets);
135 assertThat(receivedRecords.size())
136 .describedAs("Received not all sent events")
139 assertThatNoException()
140 .describedAs("Consumer should not be running")
141 .isThrownBy(() -> endlessConsumer.exitStatus());
142 assertThat(endlessConsumer.exitStatus())
143 .describedAs("Consumer should have exited abnormally")
144 .containsInstanceOf(RecordDeserializationException.class);
148 /** Helper methods for the verification of expectations */
150 void compareToCommitedOffsets(Map<TopicPartition, Long> offsetsToCheck)
152 doForCurrentOffsets((tp, offset) ->
154 Long expected = offsetsToCheck.get(tp) + 1;
155 log.debug("Checking, if the offset for {} is {}", tp, expected);
157 .describedAs("Committed offset corresponds to the offset of the consumer")
158 .isEqualTo(expected);
162 void checkSeenOffsetsForProgress()
164 // Be sure, that some messages were consumed...!
165 Set<TopicPartition> withProgress = new HashSet<>();
166 partitions().forEach(tp ->
168 Long oldOffset = oldOffsets.get(tp) + 1;
169 Long newOffset = newOffsets.get(tp) + 1;
170 if (!oldOffset.equals(newOffset))
172 log.debug("Progress for {}: {} -> {}", tp, oldOffset, newOffset);
173 withProgress.add(tp);
176 assertThat(withProgress)
177 .describedAs("Some offsets must have changed, compared to the old offset-positions")
182 /** Helper methods for setting up and running the tests */
186 offsetConsumer.assign(partitions());
187 offsetConsumer.seekToEnd(partitions());
188 partitions().forEach(tp ->
190 // seekToEnd() works lazily: it only takes effect on poll()/position()
191 Long offset = offsetConsumer.position(tp);
192 log.info("New position for {}: {}", tp, offset);
194 // The new positions must be commited!
195 offsetConsumer.commitSync();
196 offsetConsumer.unsubscribe();
199 void doForCurrentOffsets(BiConsumer<TopicPartition, Long> consumer)
201 offsetConsumer.assign(partitions());
202 partitions().forEach(tp -> consumer.accept(tp, offsetConsumer.position(tp)));
203 offsetConsumer.unsubscribe();
206 List<TopicPartition> partitions()
210 .range(0, PARTITIONS)
211 .mapToObj(partition -> new TopicPartition(TOPIC, partition))
212 .collect(Collectors.toList());
216 public interface RecordGenerator<K, V>
218 public ProducerRecord<String, Bytes> generate(int partition, String key, long counter);
221 void send100Messages(RecordGenerator recordGenerator)
225 for (int partition = 0; partition < 10; partition++)
227 for (int key = 0; key < 10; key++)
229 ProducerRecord<String, Bytes> record =
230 recordGenerator.generate(partition, Integer.toString(partition*10+key%2), ++i);
232 kafkaProducer.send(record, (metadata, e) ->
234 if (metadata != null)
238 metadata.partition(),
246 "Exception for {}={}: {}",
262 oldOffsets = new HashMap<>();
263 newOffsets = new HashMap<>();
264 receivedRecords = new HashSet<>();
266 doForCurrentOffsets((tp, offset) ->
268 oldOffsets.put(tp, offset - 1);
269 newOffsets.put(tp, offset - 1);
272 TestRecordHandler<String, Long> captureOffsetAndExecuteTestHandler =
273 new TestRecordHandler<String, Long>(keyCountingRecordHandler) {
275 public void onNewRecord(ConsumerRecord<String, Long> record)
278 new TopicPartition(record.topic(), record.partition()),
280 receivedRecords.add(record);
285 new EndlessConsumer<>(
287 properties.getClientId(),
288 properties.getTopic(),
290 keyCountingRebalanceListener,
291 captureOffsetAndExecuteTestHandler);
293 endlessConsumer.start();
301 endlessConsumer.stop();
305 log.info("Exception while stopping the consumer: {}", e.toString());
311 @Import(ApplicationConfiguration.class)
312 public static class Configuration
315 Serializer<Long> serializer()
317 return new LongSerializer();
321 KafkaProducer<String, Bytes> kafkaProducer(ApplicationProperties properties)
323 Properties props = new Properties();
324 props.put("bootstrap.servers", properties.getBootstrapServer());
325 props.put("linger.ms", 100);
326 props.put("key.serializer", StringSerializer.class.getName());
327 props.put("value.serializer", BytesSerializer.class.getName());
329 return new KafkaProducer<>(props);
333 KafkaConsumer<Bytes, Bytes> offsetConsumer(ApplicationProperties properties)
335 Properties props = new Properties();
336 props.put("bootstrap.servers", properties.getBootstrapServer());
337 props.put("client.id", "OFFSET-CONSUMER");
338 props.put("group.id", properties.getGroupId());
339 props.put("key.deserializer", BytesDeserializer.class.getName());
340 props.put("value.deserializer", BytesDeserializer.class.getName());
342 return new KafkaConsumer<>(props);