* Bisher waren alle Nachrichten vom Typ `String`.
* Jetzt verarbeitet der Adder zwei unterschiedliche Typen von Nachrichten.
* Die Nachrichten werden als JSON übertragen und mit Hilfe des
`JsonDeserializer` von Spring Kafka in zwei unterschiedliche
Spezialisierungen einer Basis-Klasse deserialisiert.
* Die für die Deserialisierung benötigte Typen-Information wird von dem
Spring-Kafka-Tooling über den die `__TypeId__` transportiert.
* D.h., damit die Nachrichten korrekt deserialisiert werden können, ist es
_nicht_ nötig, dass der Typ der Nachricht von Jackson aus der Nachricht
selbst abgeleitet werden kann, sondern dass sich Sender und Empfänger
darüber verständigen, welchen Hinweis sie in dem `__TypeId__`-Header
hinterlegen.
<optional>true</optional>
</dependency>
<dependency>
- <groupId>org.apache.kafka</groupId>
- <artifactId>kafka-clients</artifactId>
+ <groupId>org.springframework.kafka</groupId>
+ <artifactId>spring-kafka</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
+import org.springframework.kafka.support.serializer.JsonDeserializer;
import java.time.Clock;
import java.util.Optional;
ApplicationRecordHandler recordHandler,
AdderResults adderResults,
StateRepository stateRepository,
- Consumer<String, String> consumer,
+ Consumer<String, Message> consumer,
ApplicationProperties properties)
{
return new ApplicationRebalanceListener(
}
@Bean
- public EndlessConsumer<String, String> endlessConsumer(
- KafkaConsumer<String, String> kafkaConsumer,
+ public EndlessConsumer<String, Message> endlessConsumer(
+ KafkaConsumer<String, Message> kafkaConsumer,
ExecutorService executor,
ApplicationRebalanceListener rebalanceListener,
ApplicationRecordHandler recordHandler,
}
@Bean(destroyMethod = "close")
- public KafkaConsumer<String, String> kafkaConsumer(ApplicationProperties properties)
+ public KafkaConsumer<String, Message> kafkaConsumer(ApplicationProperties properties)
{
Properties props = new Properties();
props.put("auto.offset.reset", properties.getAutoOffsetReset());
props.put("metadata.max.age.ms", "1000");
props.put("key.deserializer", StringDeserializer.class.getName());
- props.put("value.deserializer", StringDeserializer.class.getName());
+ props.put("value.deserializer", JsonDeserializer.class.getName());
+ props.put(JsonDeserializer.TRUSTED_PACKAGES, "de.juplo.kafka");
+ props.put(JsonDeserializer.TYPE_MAPPINGS,
+ Message.Type.ADD + ":" + MessageAddNumber.class.getName() + "," +
+ Message.Type.CALC + ":" + MessageCalculateSum.class.getName());
return new KafkaConsumer<>(props);
}
@RequiredArgsConstructor
public class ApplicationHealthIndicator implements HealthIndicator
{
- private final EndlessConsumer<String, String> consumer;
+ private final EndlessConsumer<String, Message> consumer;
@Override
@RequiredArgsConstructor
@Slf4j
-public class ApplicationRecordHandler implements RecordHandler<String, String>
+public class ApplicationRecordHandler implements RecordHandler<String, Message>
{
private final AdderResults results;
private final Optional<Duration> throttle;
@Override
- public void accept(ConsumerRecord<String, String> record)
+ public void accept(ConsumerRecord<String, Message> record)
{
Integer partition = record.partition();
String user = record.key();
- String message = record.value();
+ Message message = record.value();
- if (message.equals("CALCULATE"))
+ switch(message.getType())
{
- AdderResult result = state.get(partition).calculate(user);
- log.info("{} - New result for {}: {}", id, user, result);
- results.addResults(partition, user, result);
- }
- else
- {
- state.get(partition).addToSum(user, Integer.parseInt(message));
+ case ADD:
+ MessageAddNumber addNumber = (MessageAddNumber)message;
+ state.get(partition).addToSum(user, addNumber.getNext());
+ break;
+
+ case CALC:
+ AdderResult result = state.get(partition).calculate(user);
+ log.info("{} - New result for {}: {}", id, user, result);
+ results.addResults(partition, user, result);
+ break;
}
if (throttle.isPresent())
--- /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;
+ }
+}
@Slf4j
-public class ApplicationTests extends GenericApplicationTests<String, String>
+public class ApplicationTests extends GenericApplicationTests<String, Message>
{
@Autowired
StateRepository stateRepository;
.mapToObj(i -> "seeräuber-" + i)
.toArray(i -> new String[i]);
final StringSerializer stringSerializer = new StringSerializer();
- final Bytes calculateMessage = new Bytes(stringSerializer.serialize(TOPIC, "CALCULATE"));
+ final Bytes calculateMessage = new Bytes(stringSerializer.serialize(TOPIC, "{}"));
int counter = 0;
if (message[i] > number[i])
{
- send(key, calculateMessage, fail(logicErrors, pass, counter), messageSender);
+ send(
+ key,
+ calculateMessage,
+ Message.Type.CALC,
+ poisonPill(poisonPills, pass, counter),
+ logicError(logicErrors, pass, counter),
+ messageSender);
state.get(seeräuber).add(new AdderResult(number[i], (number[i] + 1) * number[i] / 2));
// Pick next number to calculate
number[i] = numbers[next++%numbers.length];
log.debug("Seeräuber {} will die Summe für {} berechnen", seeräuber, number[i]);
}
- Bytes value = new Bytes(stringSerializer.serialize(TOPIC, Integer.toString(message[i]++)));
- send(key, value, fail(logicErrors, pass, counter), messageSender);
+ send(
+ key,
+ new Bytes(stringSerializer.serialize(TOPIC, "{\"next\":" + message[i]++ + "}")),
+ Message.Type.ADD,
+ poisonPill(poisonPills, pass, counter),
+ logicError(logicErrors, pass, counter),
+ messageSender);
}
}
return counter;
}
- boolean fail (boolean logicErrors, int pass, int counter)
+ boolean poisonPill (boolean poisonPills, int pass, int counter)
+ {
+ return poisonPills && pass > 300 && counter%99 == 0;
+ }
+
+ boolean logicError(boolean logicErrors, int pass, int counter)
{
return logicErrors && pass > 300 && counter%77 == 0;
}
void send(
Bytes key,
Bytes value,
- boolean fail,
+ Message.Type type,
+ boolean poisonPill,
+ boolean logicError,
Consumer<ProducerRecord<Bytes, Bytes>> messageSender)
{
counter++;
- if (fail)
+ if (logicError)
{
- value = new Bytes(stringSerializer.serialize(TOPIC, Integer.toString(-1)));
+ value = new Bytes(stringSerializer.serialize(TOPIC, "{\"next\":-1}"));
+ }
+ if (poisonPill)
+ {
+ value = new Bytes("BOOM!".getBytes());
}
- messageSender.accept(new ProducerRecord<>(TOPIC, key, value));
- }
-
- @Override
- public boolean canGeneratePoisonPill()
- {
- return false;
+ ProducerRecord<Bytes, Bytes> record = new ProducerRecord<>(TOPIC, key, value);
+ record.headers().add("__TypeId__", type.toString().getBytes());
+ messageSender.accept(record);
}
@Override
--- /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;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.junit.jupiter.params.provider.ValueSource;
+
+import java.util.Arrays;
+import java.util.stream.IntStream;
+import java.util.stream.Stream;
+
+import static org.assertj.core.api.Assertions.*;
+
+
+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));
+ }
+}