!!测试环境
生产者,它每秒发送一次带有键“ A”的消息。
Kafka Streams(Java代码)滚动窗口。
此代码将消息的数量保存在Ktable中的窗口中。
我只想简单地列出应用程序列表,以打印出我收到的消息。
!电流输出 (timestemp,键,每个翻滚窗口的邮件数)
(1544079700000L,'A',10)
(1544079710000L,'A',10)
(1544079720000L,'A',10)
...
!我想要的输出(timestemp,键,值列表)
(1544079700000L,‘A’,,=,[a,b,c,d,e,f,g,h,i,j])
(1544079710000L,'A',,=,[k,l,m,n,o,p,u,x,y,z])
(1544079710000L,'A',,=,[a,c,w,d,r,f,a,s,w,d])
...
!代码
package io.github.timothyrenner.kstreamex.tumblingwindow;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.streams.KafkaStreams;
import org.apache.kafka.streams.KeyValue;
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.Windowed;
import org.apache.kafka.streams.kstream.TimeWindows;
import org.apache.kafka.streams.kstream.KStreamBuilder;
import java.util.Properties;
import java.util.Random;
/** Demonstrates tumbling windows.
*
* @author Timothy Renner
*/
public class TumblingWindowKafkaStream {
/** Runs the streams program, writing to the "long-counts-all" topic.
*
* @param args Not used.
*/
public static void main(String[] args) throws Exception {
Properties config = new Properties();
config.put(StreamsConfig.APPLICATION_ID_CONFIG,
"tumbling-window-kafka-streams");
config.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG,
"localhost:9090,localhost:9091,localhost:9092");
config.put(StreamsConfig.ZOOKEEPER_CONNECT_CONFIG,
"localhost:2181");
config.put(StreamsConfig.KEY_SERDE_CLASS_CONFIG,
Serdes.ByteArray().getClass().getName());
config.put(StreamsConfig.VALUE_SERDE_CLASS_CONFIG,
Serdes.Long().getClass().getName());
KStreamBuilder builder = new KStreamBuilder();
KStream<byte[], byte[]> longs = builder.stream(
Serdes.ByteArray(), Serdes.ByteArray(), "t2");
// The tumbling windows will clear every ten seconds.
KTable<Windowed<byte[]>, Long> longCounts =
longs.groupByKey()
.count(TimeWindows.of(10000L)
.until(10000L),
"t2-counts");
// Write to topics.
longCounts.toStream((k,v) -> k.key())
.to(Serdes.ByteArray(),
Serdes.Long(),
"t2-counts-all");
KafkaStreams streams = new KafkaStreams(builder, config);
streams.start();
} // Close main.
} // Close TumblingWindowKafkaStream.