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 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.KafkaStreams;
14 import org.apache.kafka.streams.KeyValue;
15 import org.apache.kafka.streams.StreamsBuilder;
16 import org.apache.kafka.streams.StreamsConfig;
17 import org.apache.kafka.streams.kstream.Consumed;
18 import org.springframework.boot.SpringApplication;
19 import org.springframework.context.ConfigurableApplicationContext;
20 import org.springframework.stereotype.Component;
22 import javax.annotation.PostConstruct;
23 import javax.annotation.PreDestroy;
24 import java.util.Properties;
25 import java.util.concurrent.CompletableFuture;
26 import java.util.regex.Pattern;
28 import static org.apache.kafka.streams.errors.StreamsUncaughtExceptionHandler.StreamThreadExceptionResponse.SHUTDOWN_CLIENT;
33 public class Top10StreamProcessor
35 final static Pattern PATTERN = Pattern.compile("\\W+");
37 public final KafkaStreams streams;
40 public Top10StreamProcessor(
41 Top10ApplicationProperties properties,
43 ConfigurableApplicationContext context)
45 StreamsBuilder builder = new StreamsBuilder();
48 .<Key, Long>stream(properties.getInputTopic(), Consumed.with(SpecificAvroSerializer.class, Serdes.String()) )
49 .map((key, count) -> new KeyValue<>(
51 Entry.newBuilder().setWord(key.getWord()).setCount(count).build()))
54 () -> Ranking.newBuilder().build(),
55 (username, entry, ranking) -> {
56 ranking.getEntries().add(entry);
60 .to(properties.getOutputTopic());
62 Properties props = new Properties();
63 props.put(StreamsConfig.APPLICATION_ID_CONFIG, properties.getApplicationId());
64 props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, properties.getBootstrapServer());
65 props.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass());
66 props.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, SpecificAvroSerde.class);
67 props.put(AbstractKafkaSchemaSerDeConfig.SCHEMA_REGISTRY_URL_CONFIG, properties.getSchemaRegistry());
68 props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
70 streams = new KafkaStreams(builder.build(), props);
71 streams.setUncaughtExceptionHandler((Throwable e) ->
73 log.error("Unexpected error!", e);
74 CompletableFuture.runAsync(() ->
76 log.info("Stopping application...");
77 SpringApplication.exit(context, () -> 1);
79 return SHUTDOWN_CLIENT;
86 log.info("Starting Stream-Processor");
93 log.info("Stopping Stream-Processor");