Springify: Konfiguration erfolgt über `KafkaProperties`
[demos/kafka/training] / src / main / java / de / juplo / kafka / ApplicationConfiguration.java
1 package de.juplo.kafka;
2
3 import org.apache.kafka.clients.consumer.ConsumerRecord;
4 import org.apache.kafka.clients.consumer.KafkaConsumer;
5 import org.apache.kafka.common.serialization.LongDeserializer;
6 import org.apache.kafka.common.serialization.StringDeserializer;
7 import org.springframework.boot.autoconfigure.kafka.KafkaProperties;
8 import org.springframework.boot.context.properties.EnableConfigurationProperties;
9 import org.springframework.context.annotation.Bean;
10 import org.springframework.context.annotation.Configuration;
11
12 import java.util.Properties;
13 import java.util.concurrent.ExecutorService;
14 import java.util.concurrent.Executors;
15 import java.util.function.Consumer;
16
17
18 @Configuration
19 @EnableConfigurationProperties({ KafkaProperties.class, ApplicationProperties.class })
20 public class ApplicationConfiguration
21 {
22   @Bean
23   public Consumer<ConsumerRecord<String, Long>> consumer()
24   {
25     return (record) ->
26     {
27       // Handle record
28     };
29   }
30
31   @Bean
32   public EndlessConsumer<String, Long> endlessConsumer(
33       KafkaConsumer<String, Long> kafkaConsumer,
34       ExecutorService executor,
35       Consumer<ConsumerRecord<String, Long>> handler,
36       KafkaProperties kafkaProperties,
37       ApplicationProperties applicationProperties)
38   {
39     return
40         new EndlessConsumer<>(
41             executor,
42             kafkaProperties.getConsumer().getClientId(),
43             applicationProperties.getTopic(),
44             kafkaConsumer,
45             handler);
46   }
47
48   @Bean
49   public ExecutorService executor()
50   {
51     return Executors.newSingleThreadExecutor();
52   }
53
54   @Bean(destroyMethod = "close")
55   public KafkaConsumer<String, Long> kafkaConsumer(KafkaProperties properties)
56   {
57     Properties props = new Properties();
58
59     props.put("bootstrap.servers", properties.getConsumer().getBootstrapServers());
60     props.put("group.id", properties.getConsumer().getGroupId());
61     props.put("client.id", properties.getConsumer().getClientId());
62     props.put("auto.offset.reset", properties.getConsumer().getAutoOffsetReset());
63     props.put("metadata.max.age.ms", "1000");
64     props.put("key.deserializer", StringDeserializer.class.getName());
65     props.put("value.deserializer", LongDeserializer.class.getName());
66
67     return new KafkaConsumer<>(props);
68   }
69 }