TMP
[demos/kafka/training] / src / main / java / de / juplo / kafka / ApplicationConfiguration.java
1 package de.juplo.kafka;
2
3 import org.apache.kafka.clients.consumer.Consumer;
4 import org.apache.kafka.clients.consumer.KafkaConsumer;
5 import org.apache.kafka.common.serialization.StringDeserializer;
6 import org.springframework.boot.context.properties.EnableConfigurationProperties;
7 import org.springframework.context.annotation.Bean;
8 import org.springframework.context.annotation.Configuration;
9
10 import java.time.Clock;
11 import java.util.Properties;
12 import java.util.concurrent.ExecutorService;
13 import java.util.concurrent.Executors;
14
15
16 @Configuration
17 @EnableConfigurationProperties(ApplicationProperties.class)
18 public class ApplicationConfiguration
19 {
20   @Bean
21   public SumRecordHandler sumRecordHandler()
22   {
23     return new SumRecordHandler();
24   }
25
26   @Bean
27   public SumRebalanceListener sumRebalanceListener(
28       SumRecordHandler sumRecordHandler,
29       PartitionStatisticsRepository repository,
30       Consumer<String, String> consumer,
31       ApplicationProperties properties)
32   {
33     return new SumRebalanceListener(
34         sumRecordHandler,
35         repository,
36         properties.getClientId(),
37         properties.getTopic(),
38         Clock.systemDefaultZone(),
39         properties.getCommitInterval(),
40         consumer);
41   }
42
43   @Bean
44   public EndlessConsumer<String, String> endlessConsumer(
45       KafkaConsumer<String, String> kafkaConsumer,
46       ExecutorService executor,
47       SumRebalanceListener sumRebalanceListener,
48       SumRecordHandler sumRecordHandler,
49       ApplicationProperties properties)
50   {
51     return
52         new EndlessConsumer<>(
53             executor,
54             properties.getClientId(),
55             properties.getTopic(),
56             kafkaConsumer,
57             sumRebalanceListener,
58             sumRecordHandler);
59   }
60
61   @Bean
62   public ExecutorService executor()
63   {
64     return Executors.newSingleThreadExecutor();
65   }
66
67   @Bean(destroyMethod = "close")
68   public KafkaConsumer<String, String> kafkaConsumer(ApplicationProperties properties)
69   {
70     Properties props = new Properties();
71
72     props.put("bootstrap.servers", properties.getBootstrapServer());
73     props.put("partition.assignment.strategy", "org.apache.kafka.clients.consumer.CooperativeStickyAssignor");
74     props.put("group.id", properties.getGroupId());
75     props.put("client.id", properties.getClientId());
76     props.put("enable.auto.commit", false);
77     props.put("auto.offset.reset", properties.getAutoOffsetReset());
78     props.put("metadata.max.age.ms", "1000");
79     props.put("key.deserializer", StringDeserializer.class.getName());
80     props.put("value.deserializer", StringDeserializer.class.getName());
81
82     return new KafkaConsumer<>(props);
83   }
84 }