1 package de.juplo.kafka.wordcount.counter;
3 import com.fasterxml.jackson.databind.ObjectMapper;
4 import lombok.extern.slf4j.Slf4j;
5 import org.apache.kafka.clients.consumer.ConsumerConfig;
6 import org.apache.kafka.common.serialization.Serdes;
7 import org.apache.kafka.streams.StreamsConfig;
8 import org.apache.kafka.streams.state.KeyValueBytesStoreSupplier;
9 import org.apache.kafka.streams.state.Stores;
10 import org.springframework.boot.SpringApplication;
11 import org.springframework.boot.autoconfigure.SpringBootApplication;
12 import org.springframework.boot.context.properties.EnableConfigurationProperties;
13 import org.springframework.context.ConfigurableApplicationContext;
14 import org.springframework.context.annotation.Bean;
16 import java.util.Properties;
17 import java.util.concurrent.CompletableFuture;
19 import static org.apache.kafka.streams.errors.StreamsUncaughtExceptionHandler.StreamThreadExceptionResponse.SHUTDOWN_CLIENT;
22 @SpringBootApplication
23 @EnableConfigurationProperties(CounterApplicationProperties.class)
25 public class CounterApplication
27 @Bean(initMethod = "start", destroyMethod = "stop")
28 public CounterStreamProcessor streamProcessor(
29 CounterApplicationProperties properties,
30 KeyValueBytesStoreSupplier storeSupplier,
31 ObjectMapper objectMapper,
32 ConfigurableApplicationContext context)
34 Properties propertyMap = new Properties();
36 propertyMap.put(StreamsConfig.APPLICATION_ID_CONFIG, properties.getApplicationId());
37 propertyMap.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, properties.getBootstrapServer());
38 propertyMap.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.StringSerde.class.getName());
39 propertyMap.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.StringSerde.class.getName());
40 propertyMap.put(StreamsConfig.STATE_DIR_CONFIG, "target");
41 if (properties.getCommitInterval() != null)
42 propertyMap.put(StreamsConfig.COMMIT_INTERVAL_MS_CONFIG, properties.getCommitInterval());
43 if (properties.getCacheMaxBytes() != null)
44 propertyMap.put(StreamsConfig.CACHE_MAX_BYTES_BUFFERING_CONFIG, properties.getCacheMaxBytes());
45 propertyMap.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
47 CounterStreamProcessor streamProcessor = new CounterStreamProcessor(
48 properties.getInputTopic(),
49 properties.getOutputTopic(),
54 streamProcessor.streams.setUncaughtExceptionHandler((Throwable e) ->
56 log.error("Unexpected error!", e);
57 CompletableFuture.runAsync(() ->
59 log.info("Stopping application...");
60 SpringApplication.exit(context, () -> 1);
62 return SHUTDOWN_CLIENT;
66 return streamProcessor;
70 public KeyValueBytesStoreSupplier storeSupplier()
72 return Stores.persistentKeyValueStore("counter");
75 public static void main(String[] args)
77 SpringApplication.run(CounterApplication.class, args);