1 package de.juplo.kafka;
3 import org.apache.kafka.clients.consumer.KafkaConsumer;
4 import org.apache.kafka.common.serialization.StringDeserializer;
5 import org.springframework.boot.context.properties.EnableConfigurationProperties;
6 import org.springframework.context.ConfigurableApplicationContext;
7 import org.springframework.context.annotation.Bean;
8 import org.springframework.context.annotation.Configuration;
9 import org.springframework.kafka.support.serializer.JsonDeserializer;
11 import java.util.Optional;
12 import java.util.Properties;
13 import java.util.concurrent.ExecutorService;
14 import java.util.concurrent.Executors;
18 @EnableConfigurationProperties(ApplicationProperties.class)
19 public class ApplicationConfiguration
22 public ApplicationRecordHandler recordHandler(
23 AdderResults adderResults,
24 ApplicationProperties properties)
26 return new ApplicationRecordHandler(
28 Optional.ofNullable(properties.getThrottle()),
29 properties.getClientId());
33 public AdderResults adderResults()
35 return new AdderResults();
39 public ApplicationRebalanceListener rebalanceListener(
40 ApplicationRecordHandler recordHandler,
41 AdderResults adderResults,
42 StateRepository stateRepository,
43 KafkaConsumer<String, Message> consumer,
44 ApplicationProperties properties)
46 return new ApplicationRebalanceListener(
50 properties.getClientId());
54 public EndlessConsumer<String, Message> endlessConsumer(
55 KafkaConsumer<String, Message> kafkaConsumer,
56 ExecutorService executor,
57 ConfigurableApplicationContext applicationContext,
58 ApplicationRebalanceListener rebalanceListener,
59 ApplicationRecordHandler recordHandler,
60 ApplicationProperties properties)
63 new EndlessConsumer<>(
66 properties.getClientId(),
67 properties.getTopic(),
74 public ExecutorService executor()
76 return Executors.newSingleThreadExecutor();
79 @Bean(destroyMethod = "close")
80 public KafkaConsumer<String, Message> kafkaConsumer(ApplicationProperties properties)
82 Properties props = new Properties();
84 props.put("bootstrap.servers", properties.getBootstrapServer());
85 props.put("partition.assignment.strategy", "org.apache.kafka.clients.consumer.StickyAssignor");
86 props.put("group.id", properties.getGroupId());
87 props.put("client.id", properties.getClientId());
88 props.put("auto.offset.reset", properties.getAutoOffsetReset());
89 props.put("auto.commit.interval.ms", (int)properties.getCommitInterval().toMillis());
90 props.put("metadata.max.age.ms", "1000");
91 props.put("key.deserializer", StringDeserializer.class.getName());
92 props.put("value.deserializer", JsonDeserializer.class.getName());
93 props.put(JsonDeserializer.TRUSTED_PACKAGES, "de.juplo.kafka");
94 props.put(JsonDeserializer.TYPE_MAPPINGS,
95 Message.Type.ADD + ":" + MessageAddNumber.class.getName() + "," +
96 Message.Type.CALC + ":" + MessageCalculateSum.class.getName());
98 return new KafkaConsumer<>(props);