e88798797e2b503bb6415e1e9c6ff5276fb3e1a9
[demos/kafka/training] / src / main / java / de / juplo / kafka / ApplicationConfiguration.java
1 package de.juplo.kafka;
2
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.annotation.Bean;
7 import org.springframework.context.annotation.Configuration;
8
9 import java.util.Optional;
10 import java.util.Properties;
11 import java.util.concurrent.ExecutorService;
12 import java.util.concurrent.Executors;
13
14
15 @Configuration
16 @EnableConfigurationProperties(ApplicationProperties.class)
17 public class ApplicationConfiguration
18 {
19   @Bean
20   public ApplicationRecordHandler recordHandler(
21       AdderResults adderResults,
22       ApplicationProperties properties)
23   {
24     return new ApplicationRecordHandler(
25         adderResults,
26         Optional.ofNullable(properties.getThrottle()),
27         properties.getClientId());
28   }
29
30   @Bean
31   public AdderResults adderResults()
32   {
33     return new AdderResults();
34   }
35
36   @Bean
37   public EndlessConsumer<String, String> endlessConsumer(
38       KafkaConsumer<String, String> kafkaConsumer,
39       ExecutorService executor,
40       ApplicationRecordHandler recordHandler,
41       ApplicationProperties properties)
42   {
43     return
44         new EndlessConsumer<>(
45             executor,
46             properties.getClientId(),
47             properties.getTopic(),
48             kafkaConsumer,
49             recordHandler);
50   }
51
52   @Bean
53   public ExecutorService executor()
54   {
55     return Executors.newSingleThreadExecutor();
56   }
57
58   @Bean(destroyMethod = "close")
59   public KafkaConsumer<String, String> kafkaConsumer(ApplicationProperties properties)
60   {
61     Properties props = new Properties();
62
63     props.put("bootstrap.servers", properties.getBootstrapServer());
64     props.put("partition.assignment.strategy", "org.apache.kafka.clients.consumer.StickyAssignor");
65     props.put("group.id", properties.getGroupId());
66     props.put("client.id", properties.getClientId());
67     props.put("auto.offset.reset", properties.getAutoOffsetReset());
68     props.put("auto.commit.interval.ms", (int)properties.getCommitInterval().toMillis());
69     props.put("metadata.max.age.ms", "1000");
70     props.put("key.deserializer", StringDeserializer.class.getName());
71     props.put("value.deserializer", StringDeserializer.class.getName());
72
73     return new KafkaConsumer<>(props);
74   }
75 }