Last active
July 12, 2017 06:33
-
-
Save miguno/9d48dd80ca492d64c58dae529a60d444 to your computer and use it in GitHub Desktop.
WordCount application in Java 8+, using Kafka's Streams API (Kafka version 0.11.0.0)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.apache.kafka.common.serialization.Serdes; | |
import org.apache.kafka.streams.KafkaStreams; | |
import org.apache.kafka.streams.StreamsConfig; | |
import org.apache.kafka.streams.kstream.KStream; | |
import org.apache.kafka.streams.kstream.KStreamBuilder; | |
import org.apache.kafka.streams.kstream.KTable; | |
import java.util.Arrays; | |
import java.util.Properties; | |
public class WordCountApplication { | |
public static void main(final String[] args) throws Exception { | |
Properties config = new Properties(); | |
config.put(StreamsConfig.APPLICATION_ID_CONFIG, "wordcount-application"); | |
config.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "kafka-broker1:9092"); | |
config.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass()); | |
config.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass()); | |
KStreamBuilder builder = new KStreamBuilder(); | |
KStream<String, String> textLines = builder.stream("TextLinesTopic"); | |
KTable<String, Long> wordCounts = textLines | |
.flatMapValues(textLine -> Arrays.asList(textLine.toLowerCase().split("\\W+"))) | |
.groupBy((key, word) -> word) | |
.count("Counts"); | |
wordCounts.to(Serdes.String(), Serdes.Long(), "WordsWithCountsTopic"); | |
KafkaStreams streams = new KafkaStreams(builder, config); | |
streams.start(); | |
Runtime.getRuntime().addShutdownHook(new Thread(streams::close)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment