在Kafka流上为窗口数据创建SerDes

时间:2019-05-14 17:38:29

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

我在创建要与正在聚合的数据一起使用的SerDes时遇到了一些麻烦,并且需要通过'.to()'发送到另一个主题,但是,我需要为窗口数据创建SerDes,我不确定该怎么做。

1 个答案:

答案 0 :(得分:1)

我们可以通过以下方式为窗口数据创建Serilizer和DeSerilizer。

StringSerializer stringSerializer = new StringSerializer();
StringDeserializer stringDeserializer = new StringDeserializer();
Serde<String> stringSerde = Serdes.serdeFrom(stringSerializer,stringDeserializer);

WindowedSerializer<String> windowedSerializer = new WindowedSerializer<>(stringSerializer);
WindowedDeserializer<String> windowedDeserializer = new WindowedDeserializer<>(stringDeserializer);
Serde<Windowed<String>> windowedSerde = Serdes.serdeFrom(windowedSerializer,windowedDeserializer);

下面给出了窗口数据中Serilizer / DeSerilizer的使用。

KStream<String,StockTransaction> transactionKStream =  kStreamBuilder.stream(stringSerde,transactionSerde,"stocks");

transactionKStream.map((k,v)-> new KeyValue<>(v.getSymbol(),v))
                              .through(stringSerde, transactionSerde,"stocks-out")
                              .groupBy((k,v) -> k, stringSerde, transactionSerde)
                              .aggregate(StockTransactionCollector::new,
                                   (k, v, stockTransactionCollector) -> stockTransactionCollector.add(v),
                                   TimeWindows.of(10000),
                                   collectorSerde, "stock-summaries")
                    .to(windowedSerde,collectorSerde,"transaction-summary");

我建议您仔细阅读以下内容以获得更多信息。

https://www.programcreek.com/java-api-examples/index.php?api=org.apache.kafka.streams.kstream.internals.WindowedSerializer