wordcount:1.0.0 - counts words, keyed by username and word
[demos/kafka/wordcount] / src / main / java / de / juplo / kafka / wordcount / counter / CounterStreamProcessor.java
1 package de.juplo.kafka.wordcount.counter;
2
3 import com.fasterxml.jackson.core.JsonProcessingException;
4 import com.fasterxml.jackson.databind.ObjectMapper;
5 import lombok.extern.slf4j.Slf4j;
6 import org.apache.kafka.clients.consumer.ConsumerConfig;
7 import org.apache.kafka.common.serialization.Serdes;
8 import org.apache.kafka.streams.KafkaStreams;
9 import org.apache.kafka.streams.KeyValue;
10 import org.apache.kafka.streams.StreamsBuilder;
11 import org.apache.kafka.streams.StreamsConfig;
12 import org.apache.kafka.streams.kstream.KStream;
13 import org.springframework.boot.SpringApplication;
14 import org.springframework.context.ConfigurableApplicationContext;
15 import org.springframework.stereotype.Component;
16
17 import javax.annotation.PostConstruct;
18 import javax.annotation.PreDestroy;
19 import java.util.Arrays;
20 import java.util.Properties;
21 import java.util.concurrent.CompletableFuture;
22 import java.util.regex.Pattern;
23
24 import static org.apache.kafka.streams.errors.StreamsUncaughtExceptionHandler.StreamThreadExceptionResponse.SHUTDOWN_CLIENT;
25
26
27 @Slf4j
28 @Component
29 public class CounterStreamProcessor
30 {
31         final static Pattern PATTERN = Pattern.compile("\\W+");
32
33         public final KafkaStreams streams;
34
35
36         public CounterStreamProcessor(
37                         CounterApplicationProperties properties,
38                         ObjectMapper mapper,
39                         ConfigurableApplicationContext context)
40         {
41                 StreamsBuilder builder = new StreamsBuilder();
42
43                 KStream<String, String> source = builder.stream(properties.getInputTopic());
44                 source
45                                 .flatMapValues(sentence -> Arrays.asList(PATTERN.split(sentence)))
46                                 .map((username, word) ->
47                                 {
48                                         try
49                                         {
50                                                 String key = mapper.writeValueAsString(Key.of(username, word));
51                                                 return new KeyValue<>(key, word);
52                                         }
53                                         catch (JsonProcessingException e)
54                                         {
55                                                 throw new RuntimeException(e);
56                                         }
57                                 })
58                                 .groupByKey()
59                                 .count()
60                                 .mapValues(value->Long.toString(value))
61                                 .toStream()
62                                 .to(properties.getOutputTopic());
63
64                 Properties props = new Properties();
65                 props.put(StreamsConfig.APPLICATION_ID_CONFIG, properties.getApplicationId());
66                 props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, properties.getBootstrapServer());
67                 props.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName());
68                 props.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName());
69                 props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
70
71                 streams = new KafkaStreams(builder.build(), props);
72                 streams.setUncaughtExceptionHandler((Throwable e) ->
73                 {
74                         log.error("Unexpected error!", e);
75                         CompletableFuture.runAsync(() ->
76                         {
77                                 log.info("Stopping application...");
78                                 SpringApplication.exit(context, () -> 1);
79                         });
80                         return SHUTDOWN_CLIENT;
81                 });
82         }
83
84         @PostConstruct
85         public void start()
86         {
87                 log.info("Starting Stream-Processor");
88                 streams.start();
89         }
90
91         @PreDestroy
92         public void stop()
93         {
94                 log.info("Stopping Stream-Processor");
95                 streams.close();
96         }
97 }