1

我正在使用这样的代码向 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 Streams (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/Streams 很陌生。我该怎么做?

4

3 回答 3

1

我也是 kafka 流的新手,我不知道旧的 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));
于 2019-01-26T00:29:31.040 回答
1

要聚合两个流,您可以使用 join 方法。kstreams中有不同的连接可用。

例如:如果您想kstream加入ktable

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();
于 2018-08-22T01:01:14.637 回答
1

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

KafkaStreams streams = new KafkaStreams(builder, config);   
streams.start();    
Runtime.getRuntime().addShutdownHook(new Thread(streams::close)); 
于 2017-05-18T12:43:12.380 回答