kafka在消息中传输总字数

时间:2018-01-17 21:59:26

标签: java apache-kafka apache-kafka-streams

https://kafka.apache.org/10/documentation/streams/quickstart

我有一个关于使用kafka流计算消息中的单词的问题。从本质上讲,我想计算单词的总数,而不是计算单词的每个实例。 所以,而不是

all     1
streams 1
lead    1
to      1
kafka   1

我需要

totalWordCount   5

或类似的东西。

我在这部分代码中尝试了各种各样的事情:

KTable<String, Long> wordCounts = textLines
    .flatMapValues(value -> Arrays.asList(value.toLowerCase().split("\\W+")))
    .groupBy((key, value) -> value)
    .count();

例如添加.selectKey((key, value) -> "totalWordCount")以尝试将每个键(全部,流等)更改为totalWordCount,认为它会自行增加 我还尝试使用this编辑我的代码,以尝试实现总字数。

我没有成功,在做了更多reading之后,现在我认为我一直在接近这个错误。似乎我需要做的是有3个主题(我一直只使用2个)并且有2个生成器,其中最后一个生成器以某种方式从第一个生成器获取数据(显示每个实例的单词计数)并且基本上将数字加起来以输出单词总数,但我不完全确定如何处理它。非常感谢任何帮助/指导。感谢。

2 个答案:

答案 0 :(得分:2)

你把selectKey()放在哪里了?这个想法基本上是正确的,但请注意,groupBy()确实设置了密钥。

KTable<String, Long> wordCounts = textLines
    .flatMapValues(value -> Arrays.asList(value.toLowerCase().split("\\W+")))
    .groupBy((key, value) -> "totalWordCount")
    .count();

或(使用groupByKey()在聚合之前不更改密钥)

KTable<String, Long> wordCounts = textLines
    .selectKey((key, value) -> "totalWordCount")
    .flatMapValues(value -> Arrays.asList(value.toLowerCase().split("\\W+")))
    .groupByKey()
    .count();

答案 1 :(得分:0)

@Configuration
@EnableKafkaStreams
public class FirstStreamApp {

@Bean
public KStream<String,String> process(StreamsBuilder builder){
    KStream<String,String> inputStream = builder.stream("streamIn", Consumed.with(Serdes.String(),Serdes.String()));
    KStream<String,String> upperCaseStream = inputStream.mapValues(value->value.toUpperCase());
   upperCaseStream.to("outTopic", Produced.with(Serdes.String(),Serdes.String()));

    KTable<String, Long> wordCounts = upperCaseStream.flatMapValues(v-> Arrays.asList(v.split(" "))).selectKey((k, v) -> v).groupByKey().
           count(Materialized.<String, Long, KeyValueStore<Bytes, byte[]>>as("counts-store"));
    wordCounts.toStream().to("wordCountTopic", Produced.with(Serdes.String(),Serdes.Long()));

    return upperCaseStream;
}

}
相关问题