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.kstream.KStream;
10 import org.apache.kafka.streams.kstream.Materialized;
11 import org.apache.kafka.streams.state.KeyValueBytesStoreSupplier;
13 import java.util.Properties;
17 public class CounterStreamProcessor
19 public final KafkaStreams streams;
22 public CounterStreamProcessor(
25 Properties properties,
26 KeyValueBytesStoreSupplier storeSupplier,
29 StreamsBuilder builder = new StreamsBuilder();
31 KStream<String, String> source = builder.stream(inputTopic);
33 .map((username, word) ->
37 String key = mapper.writeValueAsString(Key.of(username, word));
38 return new KeyValue<>(key, word);
40 catch (JsonProcessingException e)
42 throw new RuntimeException(e);
46 .count(Materialized.as(storeSupplier))
47 .mapValues(value->Long.toString(value))
51 streams = new KafkaStreams(builder.build(), properties);
56 log.info("Starting Stream-Processor");
62 log.info("Stopping Stream-Processor");