<groupId>org.apache.kafka</groupId>
<artifactId>kafka-streams</artifactId>
</dependency>
+ <dependency>
+ <groupId>org.springframework.kafka</groupId>
+ <artifactId>spring-kafka</artifactId>
+ </dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
+
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
+ <dependency>
+ <groupId>org.springframework.kafka</groupId>
+ <artifactId>spring-kafka-test</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.awaitility</groupId>
+ <artifactId>awaitility</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.assertj</groupId>
+ <artifactId>assertj-core</artifactId>
+ <scope>test</scope>
+ </dependency>
</dependencies>
<build>
import org.apache.kafka.streams.KeyValue;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.kstream.KStream;
+import org.apache.kafka.streams.kstream.Produced;
+import org.springframework.kafka.support.serializer.JsonSerde;
import java.util.Properties;
public CounterStreamProcessor(
String inputTopic,
String outputTopic,
- Properties properties)
+ Properties properties,
+ ObjectMapper mapper)
{
StreamsBuilder builder = new StreamsBuilder();
- KStream<String, String> source = builder.stream(properties.getInputTopic());
+ KStream<String, Word> source = builder.stream(inputTopic);
source
- .map((username, word) ->
- {
- try
- {
- String key = mapper.writeValueAsString(Key.of(username, word));
- return new KeyValue<>(key, word);
- }
- catch (JsonProcessingException e)
- {
- throw new RuntimeException(e);
- }
- })
+ .map((key, word) -> new KeyValue<>(Key.of(word.getUser(), word.getWord()), word))
.groupByKey()
.count()
- .mapValues(value->Long.toString(value))
.toStream()
+ .map((key, count) -> new KeyValue<>(key, WordCount.of(key.getUser(), key.getWord(), count)))
+ .to(
+ outputTopic,
+ Produced.with(
+ new JsonSerde<>(Key.class)
+ .forKeys()
+ .noTypeInfo(),
+ new JsonSerde<>(WordCount.class)
+ .noTypeInfo()));
+
streams = new KafkaStreams(builder.build(), properties);
}