--- /dev/null
+package de.juplo.kafka;
+
+
+public abstract class Message
+{
+ public enum Type {ADD, CALC}
+
+ public abstract Type getType();
+}
--- /dev/null
+package de.juplo.kafka;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import lombok.Data;
+
+
+@Data
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class MessageAddNumber extends Message
+{
+ private Integer next;
+
+
+ @Override
+ public Type getType()
+ {
+ return Type.ADD;
+ }
+}
--- /dev/null
+package de.juplo.kafka;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import lombok.Data;
+
+
+@Data
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class MessageCalculateSum extends Message
+{
+ @Override
+ public Type getType()
+ {
+ return Type.CALC;
+ }
+}
{
private final String id;
private final String topic;
- private final Consumer<String, String> consumer;
+ private final Consumer<String, Message> consumer;
private long consumed = 0;
while (true)
{
- ConsumerRecords<String, String> records =
+ ConsumerRecords<String, Message> records =
consumer.poll(Duration.ofSeconds(1));
log.info("{} - Received {} messages", id, records.count());
- for (ConsumerRecord<String, String> record : records)
+ for (ConsumerRecord<String, Message> record : records)
{
consumed++;
log.info(
auto-offset-reset: earliest
auto-commit-interval: 5s
key-deserializer: org.apache.kafka.common.serialization.StringDeserializer
- value-deserializer: org.apache.kafka.common.serialization.StringDeserializer
+ value-deserializer: org.springframework.kafka.support.serializer.JsonDeserializer
properties:
partition.assignment.strategy: org.apache.kafka.clients.consumer.StickyAssignor
metadata.max.age.ms: 1000
+ spring.json.type.mapping: >
+ ADD:de.juplo.kafka.MessageAddNumber,
+ CALC:de.juplo.kafka.MessageCalculateSum
logging:
level:
root: INFO
--- /dev/null
+package de.juplo.kafka;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+
+
+public class MessageTest
+{
+ ObjectMapper mapper = new ObjectMapper();
+
+ @Test
+ @DisplayName("Deserialize a MessageAddNumber message")
+ public void testDeserializeMessageAddNumber()
+ {
+ Assertions.assertDoesNotThrow(() -> mapper.readValue("{\"next\":42}", MessageAddNumber.class));
+ Assertions.assertDoesNotThrow(() -> mapper.readValue("{\"number\":666,\"next\":42}", MessageAddNumber.class));
+ }
+
+ @Test
+ @DisplayName("Deserialize a MessageCalculateSum message")
+ public void testDeserializeMessageCalculateSum() throws JsonProcessingException
+ {
+ Assertions.assertDoesNotThrow(() -> mapper.readValue("{}", MessageCalculateSum.class));
+ Assertions.assertDoesNotThrow(() -> mapper.readValue("{\"number\":666}", MessageCalculateSum.class));
+ }
+}