811cf987147855fd443298e30a731a6c8210b48a
[demos/kafka/wordcount] / src / main / java / de / juplo / kafka / wordcount / top10 / Top10StreamProcessor.java
1 package de.juplo.kafka.wordcount.top10;
2
3 import com.fasterxml.jackson.databind.ObjectMapper;
4 import de.juplo.kafka.wordcount.avro.Entry;
5 import de.juplo.kafka.wordcount.avro.Key;
6 import de.juplo.kafka.wordcount.avro.Ranking;
7 import io.confluent.kafka.serializers.AbstractKafkaSchemaSerDeConfig;
8 import io.confluent.kafka.streams.serdes.avro.SpecificAvroSerde;
9 import io.confluent.kafka.streams.serdes.avro.SpecificAvroSerializer;
10 import lombok.extern.slf4j.Slf4j;
11 import org.apache.kafka.clients.consumer.ConsumerConfig;
12 import org.apache.kafka.common.serialization.Serdes;
13 import org.apache.kafka.streams.*;
14 import org.apache.kafka.streams.kstream.Consumed;
15 import org.apache.kafka.streams.kstream.Grouped;
16 import org.apache.kafka.streams.kstream.Materialized;
17 import org.apache.kafka.streams.kstream.Produced;
18 import org.springframework.boot.SpringApplication;
19 import org.springframework.context.ConfigurableApplicationContext;
20 import org.springframework.stereotype.Component;
21
22 import javax.annotation.PostConstruct;
23 import javax.annotation.PreDestroy;
24 import java.util.LinkedList;
25 import java.util.Properties;
26 import java.util.concurrent.CompletableFuture;
27 import java.util.regex.Pattern;
28
29 import static org.apache.kafka.streams.errors.StreamsUncaughtExceptionHandler.StreamThreadExceptionResponse.SHUTDOWN_CLIENT;
30
31
32 @Slf4j
33 @Component
34 public class Top10StreamProcessor
35 {
36         final static Pattern PATTERN = Pattern.compile("\\W+");
37
38         public final KafkaStreams streams;
39
40
41         public Top10StreamProcessor(
42                         Top10ApplicationProperties properties,
43                         ObjectMapper mapper,
44                         ConfigurableApplicationContext context)
45         {
46                 StreamsBuilder builder = new StreamsBuilder();
47
48                 builder
49                                 .<Key, Long>stream(properties.getInputTopic(), Consumed.with(null, Serdes.Long()))
50                                 .map((key, count) -> new KeyValue<>(
51                                                 key.getUsername(),
52                                                 Entry.newBuilder().setWord(key.getWord()).setCount(count).build()))
53                                 .groupByKey(Grouped.keySerde(Serdes.String()))
54                                 .aggregate(
55                                                 () -> Ranking.newBuilder().setEntries(new LinkedList<Entry>()).build(),
56                                                 (username, entry, ranking) -> {
57                                                         ranking.getEntries().add(entry);
58                                                         return ranking;
59                                                 })
60                                 .toStream()
61                                 .to(properties.getOutputTopic(), Produced.keySerde(Serdes.String()));
62
63                 Properties props = new Properties();
64                 props.put(StreamsConfig.APPLICATION_ID_CONFIG, properties.getApplicationId());
65                 props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, properties.getBootstrapServer());
66                 props.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, SpecificAvroSerde.class);
67                 props.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, SpecificAvroSerde.class);
68                 props.put(AbstractKafkaSchemaSerDeConfig.SCHEMA_REGISTRY_URL_CONFIG, properties.getSchemaRegistry());
69                 props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
70
71                 Topology topology = builder.build();
72                 log.info("Topology:\n-----------------\n\n{}-----------------", topology.describe());
73
74                 streams = new KafkaStreams(topology, props);
75                 streams.setUncaughtExceptionHandler((Throwable e) ->
76                 {
77                         log.error("Unexpected error!", e);
78                         CompletableFuture.runAsync(() ->
79                         {
80                                 log.info("Stopping application...");
81                                 SpringApplication.exit(context, () -> 1);
82                         });
83                         return SHUTDOWN_CLIENT;
84                 });
85         }
86
87         @PostConstruct
88         public void start()
89         {
90                 log.info("Starting Stream-Processor");
91                 streams.start();
92         }
93
94         @PreDestroy
95         public void stop()
96         {
97                 log.info("Stopping Stream-Processor");
98                 streams.close();
99         }
100 }