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.streams.KafkaStreams;
7 import org.apache.kafka.streams.KeyValue;
8 import org.apache.kafka.streams.StreamsBuilder;
9 import org.apache.kafka.streams.Topology;
10 import org.apache.kafka.streams.kstream.KStream;
11 import org.apache.kafka.streams.kstream.Materialized;
12 import org.apache.kafka.streams.state.KeyValueBytesStoreSupplier;
14 import java.util.Properties;
18 public class CounterStreamProcessor
20 public final KafkaStreams streams;
23 public CounterStreamProcessor(
26 Properties properties,
27 KeyValueBytesStoreSupplier storeSupplier,
30 Topology topology = CounterStreamProcessor.buildTopology(
36 streams = new KafkaStreams(topology, properties);
39 static Topology buildTopology(
42 KeyValueBytesStoreSupplier storeSupplier,
45 StreamsBuilder builder = new StreamsBuilder();
47 KStream<String, String> source = builder.stream(inputTopic);
49 .map((username, word) ->
53 String key = mapper.writeValueAsString(Key.of(username, word));
54 return new KeyValue<>(key, word);
56 catch (JsonProcessingException e)
58 throw new RuntimeException(e);
62 .count(Materialized.as(storeSupplier))
63 .mapValues(value->Long.toString(value))
67 return builder.build();
72 log.info("Starting Stream-Processor");
78 log.info("Stopping Stream-Processor");