b077a90efc137edc525dc5d57ccc7174b00c5091
[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 WordcountRecordHandler wordcountRecordHandler(
22       PartitionStatisticsRepository repository,
23       Consumer<String, String> consumer,
24       ApplicationProperties properties)
25   {
26     return new WordcountRecordHandler(
27         repository,
28         properties.getClientId(),
29         properties.getTopic(),
30         Clock.systemDefaultZone(),
31         properties.getCommitInterval(),
32         consumer);
33   }
34
35   @Bean
36   public EndlessConsumer<String, String> endlessConsumer(
37       KafkaConsumer<String, String> kafkaConsumer,
38       ExecutorService executor,
39       WordcountRecordHandler wordcountRecordHandler,
40       ApplicationProperties properties)
41   {
42     return
43         new EndlessConsumer<>(
44             executor,
45             properties.getClientId(),
46             properties.getTopic(),
47             kafkaConsumer,
48             wordcountRecordHandler);
49   }
50
51   @Bean
52   public ExecutorService executor()
53   {
54     return Executors.newSingleThreadExecutor();
55   }
56
57   @Bean(destroyMethod = "close")
58   public KafkaConsumer<String, String> kafkaConsumer(ApplicationProperties properties)
59   {
60     Properties props = new Properties();
61
62     props.put("bootstrap.servers", properties.getBootstrapServer());
63     props.put("partition.assignment.strategy", "org.apache.kafka.clients.consumer.CooperativeStickyAssignor");
64     props.put("group.id", properties.getGroupId());
65     props.put("client.id", properties.getClientId());
66     props.put("enable.auto.commit", false);
67     props.put("auto.offset.reset", properties.getAutoOffsetReset());
68     props.put("metadata.max.age.ms", "1000");
69     props.put("key.deserializer", StringDeserializer.class.getName());
70     props.put("value.deserializer", StringDeserializer.class.getName());
71
72     return new KafkaConsumer<>(props);
73   }
74 }