使用kafka流聚合流数据

8hhllhi2  于 2021-06-07  发布在  Kafka
关注(0)|答案(3)|浏览(336)

我在给Kafka发信息,代码如下:

Properties props = new Properties();
props.put("bootstrap.servers", "localhost:9092");
props.put("acks", "all");
props.put("retries", 0);
props.put("batch.size", 16384);
props.put("linger.ms", 1);
props.put("buffer.memory", 33554432);
props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");
props.put(StreamsConfig.APPLICATION_ID_CONFIG, "testo");
props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");

Producer<String, String> producer = new KafkaProducer<>(props);

for (int i = 0; i < 1000; i++) {
  producer.send(new ProducerRecord<>(
    "topico",
    String.format("{\"type\":\"test\", \"t\":%.3f, \"k\":%d}", System.nanoTime() * 1e-9, i)));
}

我想用kafka流(0.10.0.1)计算过去一小时内的消息总数。我试过了:

final KStreamBuilder builder = new KStreamBuilder();
final KStream<String, String> metrics = builder.stream(Serdes.String(), Serdes.String(), "topico");
metrics.countByKey(TimeWindows.of("Hourly", 3600 * 1000)).mapValues(Object::toString).to("output");

我对Kafka/溪流太陌生了。我该怎么做?

rnmwe5a2

rnmwe5a21#

我对kafka流也很陌生,我不知道旧的api,但是有了新的api(2.1.x),类似的东西应该可以用

kstream.mapValues((readOnlyKey, value) -> "test")
                    .groupByKey()
                    .windowedBy(TimeWindows.of(1000 * 60))
                    .count()
                    .toStream()
                    .selectKey((key, value) -> Instant.ofEpochMilli(key.window().end())
                            .truncatedTo(ChronoUnit.HOURS).toEpochMilli())
                    .groupByKey(Serialized.with(Serdes.Long(), Serdes.Long())).reduce((reduce, newVal) -> reduce + newVal)
                    .toStream().peek((key, value) -> log.info("{}={}",key,value));
anauzrmj

anauzrmj2#

首先。。您缺少此代码来实际启动流式处理。。

KafkaStreams streams = new KafkaStreams(builder, config);   
streams.start();    
Runtime.getRuntime().addShutdownHook(new Thread(streams::close));
bd1hkmkf

bd1hkmkf3#

要聚合两个流,可以使用join方法。kstream中提供了不同的连接。
例如:如果你想加入 kstreamktable :

KStream<String, String> left = builder.stream("topic1");
KTable<String, String> right = builder.table("topic2");

left.leftjoin((right, (leftValue, rightValue) -> Customfunction(rightValue, leftValue))

最后启动kstream

streams = new KafkaStreams(topology, config);
streams.start();

相关问题