介绍
- Kafka在0.10.0.0版本以前的定位是分布式,分区化的,带备份机制的日志提交服务。
- 在这之前kafka也没有提供数据处理的服务。
- 大家的流处理计算主要是还是依赖于Spark Streaming,Flink等流式处理框架。
- 但是他们都离不开Kafka的消息中转,所以Kafka于0.10.0.0版本推出了自己的流处理框架,Kafka Streams。
- Kafka的定位也正式变成为了Apache Kafka® is a distributed streaming platform,分布式流处理平台
- 目前KafkaStreams在实际中用的不多
- 流式数据计算方面用的更多的还是SparkStreaming和Flink,他们更专业
需求
- 从teststream主题接收数据,并做单词统计
- 如:
- 输入 kafka kafka spark spark spark ,
- 得出kafka 2 spark 3
代码演示
准备主题
kafka-topics.sh --zookeeper node01:2181 --create --topic teststream --replication-factor 2 --partitions 3
启动控制台生产者发送单词
kafka-console-producer.sh --broker-list node01:9092 --topic teststream
package cn.hanjiaxiaozhi.stream;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.common.utils.Bytes;
import org.apache.kafka.streams.KafkaStreams;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.StreamsConfig;
import org.apache.kafka.streams.kstream.KStream;
import org.apache.kafka.streams.kstream.KTable;
import org.apache.kafka.streams.kstream.Materialized;
import org.apache.kafka.streams.state.KeyValueStore;
import java.util.Arrays;
import java.util.Properties;
public class WordCount {
public static void main(String[] args) {
Properties props = new Properties();
props.put(StreamsConfig.APPLICATION_ID_CONFIG, "MyWordCount");
props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "node01:9092");
props.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass());
props.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass());
StreamsBuilder builder = new StreamsBuilder();
KStream<String, String> textLines = builder.stream("teststream");
KTable<String, Long> wordCounts = textLines
.flatMapValues(textLine -> Arrays.asList(textLine.toLowerCase().split("\\W+")))
.groupBy((key, word) -> word)
.count(Materialized.<String, Long, KeyValueStore<Bytes, byte[]>>as("counts-store"));
wordCounts.foreach((k,v)-> System.out.println(k+" : "+v));
KafkaStreams streams = new KafkaStreams(builder.build(), props);
streams.start();
}
}