1 package de.juplo.kafka;
4 import lombok.extern.slf4j.Slf4j;
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.serialization.*;
10 import org.apache.kafka.common.utils.Bytes;
11 import org.junit.jupiter.api.*;
12 import org.springframework.beans.factory.annotation.Autowired;
13 import org.springframework.boot.autoconfigure.kafka.KafkaAutoConfiguration;
14 import org.springframework.boot.autoconfigure.kafka.KafkaProperties;
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.context.annotation.Primary;
20 import org.springframework.kafka.listener.adapter.ConsumerRecordMetadata;
21 import org.springframework.kafka.support.serializer.JsonSerializer;
22 import org.springframework.kafka.test.context.EmbeddedKafka;
23 import org.springframework.test.context.TestPropertySource;
24 import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
26 import java.time.Duration;
27 import java.time.LocalDateTime;
29 import java.util.function.BiConsumer;
30 import java.util.function.BiFunction;
31 import java.util.stream.Collectors;
32 import java.util.stream.IntStream;
34 import static de.juplo.kafka.ApplicationTests.PARTITIONS;
35 import static de.juplo.kafka.ApplicationTests.TOPIC;
36 import static org.assertj.core.api.Assertions.*;
37 import static org.awaitility.Awaitility.*;
41 initializers = ConfigDataApplicationContextInitializer.class,
43 EndlessConsumer.class,
44 KafkaAutoConfiguration.class,
45 ApplicationTests.Configuration.class })
48 "spring.kafka.consumer.bootstrap-servers=${spring.embedded.kafka.brokers}",
49 "spring.kafka.producer.bootstrap-servers=${spring.embedded.kafka.brokers}",
50 "consumer.topic=" + TOPIC })
51 @EmbeddedKafka(topics = TOPIC, partitions = PARTITIONS)
53 class ApplicationTests
55 public static final String TOPIC = "FOO";
56 public static final int PARTITIONS = 10;
60 Serializer valueSerializer;
62 KafkaProducer<String, Bytes> kafkaProducer;
64 KafkaConsumer<Bytes, Bytes> offsetConsumer;
66 ApplicationProperties applicationProperties;
68 KafkaProperties kafkaProperties;
70 EndlessConsumer endlessConsumer;
72 MessageHandler<ClientMessage> clientMessageHandler;
74 MessageHandler<Greeting> greetingsHandler;
76 Map<TopicPartition, Long> oldOffsets;
77 Map<TopicPartition, Long> newOffsets;
84 void commitsCurrentOffsetsOnSuccess()
86 send100Messages((key, counter) -> serializeAsClientMessage(key, counter));
88 await("100 records received")
89 .atMost(Duration.ofSeconds(30))
90 .until(() -> received.size() == 100);
92 await("Offsets committed")
93 .atMost(Duration.ofSeconds(10))
96 checkSeenOffsetsForProgress();
97 compareToCommitedOffsets(newOffsets);
100 assertThat(endlessConsumer.isRunning())
101 .describedAs("Consumer should still be running")
109 send100Messages((key, counter) ->
111 ? serializeAsGreeting(key)
112 : serializeAsClientMessage(key, counter));
114 await("100 records received")
115 .atMost(Duration.ofSeconds(30))
116 .until(() -> received.size() == 100);
118 await("Offsets committed")
119 .atMost(Duration.ofSeconds(10))
122 checkSeenOffsetsForProgress();
123 compareToCommitedOffsets(newOffsets);
126 assertThat(endlessConsumer.isRunning())
127 .describedAs("Consumer should still be running")
132 void commitsCurrentOffsetsOnDeserializationError()
134 send100Messages((key, counter) ->
136 ? serializeString("BOOM!", "message")
137 : serializeAsClientMessage(key, counter));
139 await("99 records received")
140 .atMost(Duration.ofSeconds(30))
141 .until(() -> received.size() == 99);
143 await("Offsets committed")
144 .atMost(Duration.ofSeconds(10))
148 // Funktioniert nur, weil nach der Nachrichten, die den
149 // Deserialisierungs-Fehler auslöst noch valide Nachrichten
152 // Der MessageHandler sieht den Offset der Fehlerhaften
154 checkSeenOffsetsForProgress();
155 compareToCommitedOffsets(newOffsets);
158 assertThat(endlessConsumer.isRunning())
159 .describedAs("Consumer should still be running")
164 void commitsOffsetOnProgramLogicErrorFoo()
166 clientMessageHandler.testHandler = (clientMessage, metadata) ->
168 if (Integer.parseInt(clientMessage.message)%10 ==0)
169 throw new RuntimeException("BOOM: " + clientMessage.message + "%10 == 0");
172 send100Messages((key, counter) -> serializeAsClientMessage(key, counter));
174 await("80 records received")
175 .atMost(Duration.ofSeconds(30))
176 .until(() -> received.size() == 100);
178 await("Offsets committed")
179 .atMost(Duration.ofSeconds(10))
180 .pollDelay(Duration.ofSeconds(1))
183 checkSeenOffsetsForProgress();
184 compareToCommitedOffsets(newOffsets);
187 assertThat(endlessConsumer.isRunning())
188 .describedAs("Consumer should still be running")
193 /** Helper methods for the verification of expectations */
195 void compareToCommitedOffsets(Map<TopicPartition, Long> offsetsToCheck)
197 doForCurrentOffsets((tp, offset) ->
199 Long expected = offsetsToCheck.get(tp) + 1;
200 log.debug("TEST: Comparing the expected offset of {} for {} to {}", expected, tp, offset);
202 .describedAs("Committed offset corresponds to the offset of the consumer")
203 .isEqualTo(expected);
207 void checkSeenOffsetsForProgress()
209 // Be sure, that some messages were consumed...!
210 Set<TopicPartition> withProgress = new HashSet<>();
211 partitions().forEach(tp ->
213 Long oldOffset = oldOffsets.get(tp);
214 Long newOffset = newOffsets.get(tp);
215 if (!oldOffset.equals(newOffset))
217 log.debug("TEST: Progress for {}: {} -> {}", tp, oldOffset, newOffset);
218 withProgress.add(tp);
221 log.debug("TEST: Offsets with progress: {}", withProgress);
222 assertThat(withProgress)
223 .describedAs("Some offsets must have changed, compared to the old offset-positions")
228 /** Helper methods for setting up and running the tests */
230 void doForCurrentOffsets(BiConsumer<TopicPartition, Long> consumer)
232 offsetConsumer.assign(partitions());
233 partitions().forEach(tp -> consumer.accept(tp, offsetConsumer.position(tp)));
234 offsetConsumer.unsubscribe();
237 List<TopicPartition> partitions()
241 .range(0, PARTITIONS)
242 .mapToObj(partition -> new TopicPartition(TOPIC, partition))
243 .collect(Collectors.toList());
247 void send100Messages(BiFunction<Integer, Long, BytesAndType> recordGenerator)
251 for (int partition = 0; partition < 10; partition++)
253 for (int key = 0; key < 10; key++)
255 BytesAndType bat = recordGenerator.apply(key, ++i);
257 ProducerRecord<String, Bytes> record =
258 new ProducerRecord<>(
261 Integer.toString(key%2),
264 record.headers().add("__TypeId__", bat.getType());
265 kafkaProducer.send(record, (metadata, e) ->
267 if (metadata != null)
270 "TEST: Sending partition={}, offset={} - {}={}",
271 metadata.partition(),
279 "TEST: Exception for {}={}: {}",
289 BytesAndType serializeAsClientMessage(Integer key, Long value)
291 ClientMessage message = new ClientMessage();
292 message.setClient(key.toString());
293 message.setMessage(value.toString());
294 return new BytesAndType(serialize(message), "message");
297 BytesAndType serializeAsGreeting(Integer key)
299 Greeting greeting = new Greeting();
300 greeting.setName(key.toString());
301 greeting.setWhen(LocalDateTime.now());
302 return new BytesAndType(serialize(greeting), "greeting");
305 BytesAndType serializeString(String message, String messageType)
307 return new BytesAndType(new Bytes(message.getBytes()), messageType);
310 Bytes serialize(Object message)
312 return new Bytes(valueSerializer.serialize(TOPIC, message));
319 clientMessageHandler.testHandler = (clientMessage, metadata) -> {};
320 greetingsHandler.testHandler = (greeting, metadata) -> {};
322 oldOffsets = new HashMap<>();
323 newOffsets = new HashMap<>();
324 received = new HashSet<>();
326 doForCurrentOffsets((tp, offset) ->
328 oldOffsets.put(tp, offset - 1);
329 newOffsets.put(tp, offset - 1);
332 BiConsumer<?, ConsumerRecordMetadata> captureOffsets =
333 (clientMessage, metadata) ->
335 received.add(clientMessage);
336 log.debug("TEST: Processing record #{}: {}", received.size(), clientMessage);
338 new TopicPartition(metadata.topic(), metadata.partition()), metadata.offset());
341 clientMessageHandler.captureOffsets =
342 (BiConsumer<ClientMessage, ConsumerRecordMetadata>)captureOffsets;
343 greetingsHandler.captureOffsets =
344 (BiConsumer<Greeting, ConsumerRecordMetadata>)captureOffsets;
346 endlessConsumer.start();
354 endlessConsumer.stop();
358 log.info("TEST: Exception while stopping the consumer: {}", e.toString());
362 public static class MessageHandler<T> implements BiConsumer<T, ConsumerRecordMetadata>
364 BiConsumer<T, ConsumerRecordMetadata> captureOffsets;
365 BiConsumer<T, ConsumerRecordMetadata> testHandler;
369 public void accept(T message, ConsumerRecordMetadata metadata)
372 .andThen(testHandler)
373 .accept(message, metadata);
378 @Import(ApplicationConfiguration.class)
379 public static class Configuration
383 public MessageHandler<ClientMessage> messageHandler()
385 return new MessageHandler<>();
390 public MessageHandler<Greeting> greetingsHandler()
392 return new MessageHandler<>();
396 Serializer<ClientMessage> serializer()
398 return new JsonSerializer<>();
402 KafkaProducer<String, Bytes> kafkaProducer(KafkaProperties properties)
404 Properties props = new Properties();
405 props.put("bootstrap.servers", properties.getConsumer().getBootstrapServers());
406 props.put("linger.ms", 100);
407 props.put("key.serializer", StringSerializer.class.getName());
408 props.put("value.serializer", BytesSerializer.class.getName());
410 return new KafkaProducer<>(props);
414 KafkaConsumer<Bytes, Bytes> offsetConsumer(KafkaProperties properties)
416 Properties props = new Properties();
417 props.put("bootstrap.servers", properties.getConsumer().getBootstrapServers());
418 props.put("client.id", "OFFSET-CONSUMER");
419 props.put("group.id", properties.getConsumer().getGroupId());
420 props.put("key.deserializer", BytesDeserializer.class.getName());
421 props.put("value.deserializer", BytesDeserializer.class.getName());
423 return new KafkaConsumer<>(props);
429 static class BytesAndType
431 private final Bytes value;
432 private final byte[] type;
435 BytesAndType(Bytes value, String type)
438 this.type = type.getBytes();