1 package de.juplo.kafka.wordcount.counter;
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;
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;
24 import static org.apache.kafka.streams.errors.StreamsUncaughtExceptionHandler.StreamThreadExceptionResponse.SHUTDOWN_CLIENT;
29 public class CounterStreamProcessor
31 final static Pattern PATTERN = Pattern.compile("\\W+");
33 public final KafkaStreams streams;
36 public CounterStreamProcessor(
37 CounterApplicationProperties properties,
39 ConfigurableApplicationContext context)
41 StreamsBuilder builder = new StreamsBuilder();
43 KStream<String, String> source = builder.stream(properties.getInputTopic());
45 .flatMapValues(sentence -> Arrays.asList(PATTERN.split(sentence)))
46 .map((username, word) ->
50 String key = mapper.writeValueAsString(Key.of(username, word));
51 return new KeyValue<>(key, word);
53 catch (JsonProcessingException e)
55 throw new RuntimeException(e);
60 .mapValues(value->Long.toString(value))
62 .to(properties.getOutputTopic());
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");
71 streams = new KafkaStreams(builder.build(), props);
72 streams.setUncaughtExceptionHandler((Throwable e) ->
74 log.error("Unexpected error!", e);
75 CompletableFuture.runAsync(() ->
77 log.info("Stopping application...");
78 SpringApplication.exit(context, () -> 1);
80 return SHUTDOWN_CLIENT;
87 log.info("Starting Stream-Processor");
94 log.info("Stopping Stream-Processor");