1 package de.juplo.kafka.wordcount.top10;
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 lombok.extern.slf4j.Slf4j;
10 import org.apache.kafka.clients.consumer.ConsumerConfig;
11 import org.apache.kafka.common.serialization.Serdes;
12 import org.apache.kafka.streams.KafkaStreams;
13 import org.apache.kafka.streams.KeyValue;
14 import org.apache.kafka.streams.StreamsBuilder;
15 import org.apache.kafka.streams.StreamsConfig;
16 import org.springframework.boot.SpringApplication;
17 import org.springframework.context.ConfigurableApplicationContext;
18 import org.springframework.stereotype.Component;
20 import javax.annotation.PostConstruct;
21 import javax.annotation.PreDestroy;
22 import java.util.Properties;
23 import java.util.concurrent.CompletableFuture;
24 import java.util.regex.Pattern;
26 import static org.apache.kafka.streams.errors.StreamsUncaughtExceptionHandler.StreamThreadExceptionResponse.SHUTDOWN_CLIENT;
31 public class Top10StreamProcessor
33 final static Pattern PATTERN = Pattern.compile("\\W+");
35 public final KafkaStreams streams;
38 public Top10StreamProcessor(
39 Top10ApplicationProperties properties,
41 ConfigurableApplicationContext context)
43 StreamsBuilder builder = new StreamsBuilder();
46 .<Key, Long>stream(properties.getInputTopic())
47 .map((key, count) -> new KeyValue<>(
49 Entry.newBuilder().setWord(key.getWord()).setCount(count).build()))
52 () -> Ranking.newBuilder().build(),
53 (username, entry, ranking) -> {
54 ranking.getEntries().add(entry);
58 .to(properties.getOutputTopic());
60 Properties props = new Properties();
61 props.put(StreamsConfig.APPLICATION_ID_CONFIG, properties.getApplicationId());
62 props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, properties.getBootstrapServer());
63 props.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass());
64 props.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, SpecificAvroSerde.class);
65 props.put(AbstractKafkaSchemaSerDeConfig.SCHEMA_REGISTRY_URL_CONFIG, properties.getSchemaRegistry());
66 props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
68 streams = new KafkaStreams(builder.build(), props);
69 streams.setUncaughtExceptionHandler((Throwable e) ->
71 log.error("Unexpected error!", e);
72 CompletableFuture.runAsync(() ->
74 log.info("Stopping application...");
75 SpringApplication.exit(context, () -> 1);
77 return SHUTDOWN_CLIENT;
84 log.info("Starting Stream-Processor");
91 log.info("Stopping Stream-Processor");