1 package de.juplo.kafka.wordcount.counter;
3 import com.fasterxml.jackson.databind.ObjectMapper;
4 import de.juplo.kafka.wordcount.avro.Key;
5 import io.confluent.kafka.serializers.AbstractKafkaSchemaSerDeConfig;
6 import io.confluent.kafka.streams.serdes.avro.SpecificAvroSerde;
7 import lombok.extern.slf4j.Slf4j;
8 import org.apache.kafka.clients.consumer.ConsumerConfig;
9 import org.apache.kafka.common.serialization.Serdes;
10 import org.apache.kafka.streams.KafkaStreams;
11 import org.apache.kafka.streams.KeyValue;
12 import org.apache.kafka.streams.StreamsBuilder;
13 import org.apache.kafka.streams.StreamsConfig;
14 import org.apache.kafka.streams.kstream.Consumed;
15 import org.apache.kafka.streams.kstream.KStream;
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.Arrays;
23 import java.util.Properties;
24 import java.util.concurrent.CompletableFuture;
25 import java.util.regex.Pattern;
27 import static org.apache.kafka.streams.errors.StreamsUncaughtExceptionHandler.StreamThreadExceptionResponse.SHUTDOWN_CLIENT;
32 public class CounterStreamProcessor
34 final static Pattern PATTERN = Pattern.compile("\\W+");
36 public final KafkaStreams streams;
39 public CounterStreamProcessor(
40 CounterApplicationProperties properties,
42 ConfigurableApplicationContext context)
44 StreamsBuilder builder = new StreamsBuilder();
46 KStream<String, String> source =
48 properties.getInputTopic(),
49 Consumed.with(Serdes.String(), Serdes.String()));
52 .flatMapValues(sentence -> Arrays.asList(PATTERN.split(sentence)))
53 .map((username, word) ->
55 Key.newBuilder().setUsername(username).setWord(word).build(),
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, SpecificAvroSerde.class);
66 props.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.Long().getClass().getName());
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");