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.kafka.KafkaAutoConfiguration;
15 import org.springframework.boot.autoconfigure.kafka.KafkaProperties;
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.context.annotation.Primary;
21 import org.springframework.kafka.listener.MessageListenerContainer;
22 import org.springframework.kafka.support.serializer.JsonSerializer;
23 import org.springframework.kafka.test.context.EmbeddedKafka;
24 import org.springframework.test.context.TestPropertySource;
25 import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
27 import java.time.Duration;
29 import java.util.concurrent.ExecutionException;
30 import java.util.function.BiConsumer;
31 import java.util.function.BiFunction;
32 import java.util.function.Consumer;
33 import java.util.stream.Collectors;
34 import java.util.stream.IntStream;
36 import static de.juplo.kafka.ApplicationTests.PARTITIONS;
37 import static de.juplo.kafka.ApplicationTests.TOPIC;
38 import static org.assertj.core.api.Assertions.*;
39 import static org.awaitility.Awaitility.*;
43 initializers = ConfigDataApplicationContextInitializer.class,
45 EndlessConsumer.class,
46 KafkaAutoConfiguration.class,
47 ApplicationTests.Configuration.class })
48 @TestMethodOrder(MethodOrderer.OrderAnnotation.class)
51 "spring.kafka.consumer.bootstrap-servers=${spring.embedded.kafka.brokers}",
52 "spring.kafka.producer.bootstrap-servers=${spring.embedded.kafka.brokers}",
53 "consumer.topic=" + TOPIC })
54 @EmbeddedKafka(topics = TOPIC, partitions = PARTITIONS)
56 class ApplicationTests
58 public static final String TOPIC = "FOO";
59 public static final int PARTITIONS = 10;
62 StringSerializer stringSerializer = new StringSerializer();
65 Serializer valueSerializer;
67 KafkaProducer<String, Bytes> kafkaProducer;
69 org.apache.kafka.clients.consumer.Consumer<String, ClientMessage> kafkaConsumer;
71 KafkaConsumer<Bytes, Bytes> offsetConsumer;
73 ApplicationProperties applicationProperties;
75 KafkaProperties kafkaProperties;
77 EndlessConsumer endlessConsumer;
79 RecordHandler recordHandler;
81 Map<TopicPartition, Long> oldOffsets;
82 Map<TopicPartition, Long> newOffsets;
83 Set<ConsumerRecord<String, ClientMessage>> receivedRecords;
89 @Order(1) // << The poistion pill is not skipped. Hence, this test must run first
90 void commitsCurrentOffsetsOnSuccess() throws ExecutionException, InterruptedException
92 send100Messages((key, counter) -> serialize(key, counter));
94 await("100 records received")
95 .atMost(Duration.ofSeconds(30))
96 .until(() -> receivedRecords.size() == 100);
98 await("Offsets committed")
99 .atMost(Duration.ofSeconds(10))
102 checkSeenOffsetsForProgress();
103 compareToCommitedOffsets(newOffsets);
106 assertThat(endlessConsumer.isRunning())
107 .describedAs("Consumer should still be running")
113 void commitsCurrentOffsetsOnError()
115 send100Messages((key, counter) ->
117 ? new Bytes(stringSerializer.serialize(TOPIC, "BOOM!"))
118 : serialize(key, counter));
120 await("99 records received")
121 .atMost(Duration.ofSeconds(30))
122 .until(() -> receivedRecords.size() == 99);
124 await("Offsets committed")
125 .atMost(Duration.ofSeconds(10))
129 // Funktioniert nur, weil nach der Nachrichten, die den
130 // Deserialisierungs-Fehler auslöst noch valide Nachrichten
133 // Der MessageHandler sieht den Offset der Fehlerhaften
135 checkSeenOffsetsForProgress();
136 compareToCommitedOffsets(newOffsets);
139 assertThat(endlessConsumer.isRunning())
140 .describedAs("Consumer should still be running")
145 /** Helper methods for the verification of expectations */
147 void compareToCommitedOffsets(Map<TopicPartition, Long> offsetsToCheck)
149 doForCurrentOffsets((tp, offset) ->
151 Long expected = offsetsToCheck.get(tp) + 1;
152 log.debug("Checking, if the offset for {} is {}", tp, expected);
154 .describedAs("Committed offset corresponds to the offset of the consumer")
155 .isEqualTo(expected);
159 void checkSeenOffsetsForProgress()
161 // Be sure, that some messages were consumed...!
162 Set<TopicPartition> withProgress = new HashSet<>();
163 partitions().forEach(tp ->
165 Long oldOffset = oldOffsets.get(tp);
166 Long newOffset = newOffsets.get(tp);
167 if (!oldOffset.equals(newOffset))
169 log.debug("Progress for {}: {} -> {}", tp, oldOffset, newOffset);
170 withProgress.add(tp);
173 assertThat(withProgress)
174 .describedAs("Some offsets must have changed, compared to the old offset-positions")
179 /** Helper methods for setting up and running the tests */
181 void doForCurrentOffsets(BiConsumer<TopicPartition, Long> consumer)
183 offsetConsumer.assign(partitions());
184 partitions().forEach(tp -> consumer.accept(tp, offsetConsumer.position(tp)));
185 offsetConsumer.unsubscribe();
188 List<TopicPartition> partitions()
192 .range(0, PARTITIONS)
193 .mapToObj(partition -> new TopicPartition(TOPIC, partition))
194 .collect(Collectors.toList());
198 void send100Messages(BiFunction<Integer, Long, Bytes> messageGenerator)
202 for (int partition = 0; partition < 10; partition++)
204 for (int key = 0; key < 10; key++)
206 Bytes value = messageGenerator.apply(key, ++i);
208 ProducerRecord<String, Bytes> record =
209 new ProducerRecord<>(
212 Integer.toString(key%2),
215 record.headers().add("__TypeId__", "message".getBytes());
216 kafkaProducer.send(record, (metadata, e) ->
218 if (metadata != null)
222 metadata.partition(),
230 "Exception for {}={}: {}",
240 Bytes serialize(Integer key, Long value)
242 ClientMessage message = new ClientMessage();
243 message.setClient(key.toString());
244 message.setMessage(value.toString());
245 return new Bytes(valueSerializer.serialize(TOPIC, message));
252 recordHandler.testHandler = (record) -> {};
254 oldOffsets = new HashMap<>();
255 newOffsets = new HashMap<>();
256 receivedRecords = new HashSet<>();
258 doForCurrentOffsets((tp, offset) ->
260 oldOffsets.put(tp, offset - 1);
261 newOffsets.put(tp, offset - 1);
264 recordHandler.captureOffsets =
267 receivedRecords.add(record);
269 new TopicPartition(record.topic(), record.partition()),
273 endlessConsumer.start();
281 endlessConsumer.stop();
285 log.info("Exception while stopping the consumer: {}", e.toString());
289 public static class RecordHandler implements Consumer<ConsumerRecord<String, ClientMessage>>
291 Consumer<ConsumerRecord<String, ClientMessage>> captureOffsets;
292 Consumer<ConsumerRecord<String, ClientMessage>> testHandler;
296 public void accept(ConsumerRecord<String, ClientMessage> record)
299 .andThen(testHandler)
305 @Import(ApplicationConfiguration.class)
306 public static class Configuration
310 public Consumer<ConsumerRecord<String, ClientMessage>> testHandler()
312 return new RecordHandler();
316 Serializer<ClientMessage> serializer()
318 return new JsonSerializer<>();
322 KafkaProducer<String, Bytes> kafkaProducer(KafkaProperties properties)
324 Properties props = new Properties();
325 props.put("bootstrap.servers", properties.getConsumer().getBootstrapServers());
326 props.put("linger.ms", 100);
327 props.put("key.serializer", StringSerializer.class.getName());
328 props.put("value.serializer", BytesSerializer.class.getName());
330 return new KafkaProducer<>(props);
334 KafkaConsumer<Bytes, Bytes> offsetConsumer(KafkaProperties properties)
336 Properties props = new Properties();
337 props.put("bootstrap.servers", properties.getConsumer().getBootstrapServers());
338 props.put("client.id", "OFFSET-CONSUMER");
339 props.put("group.id", properties.getConsumer().getGroupId());
340 props.put("key.deserializer", BytesDeserializer.class.getName());
341 props.put("value.deserializer", BytesDeserializer.class.getName());
343 return new KafkaConsumer<>(props);