我想编写一个小型 Kafka Streams 应用程序,它减少输入流的时间窗口,对值进行一些映射,然后将结果更改日志 toStream() 发送到另一个主题。
使用我的代码,我在 toStream() 操作中收到以下错误:

Compilation failure
[ERROR] StreamFilter.java:[39,86] incompatible types: org.apache.kafka.streams.kstream.KStream<org.apache.kafka.streams.kstream.Windowed<java.lang.Integer>,filterExample.SensorMessage> cannot be converted to org.apache.kafka.streams.kstream.KStream<java.lang.Integer,filterExample.SensorMessage>

我在某处读到默认的 Serdes 可能是问题所在,但到目前为止,将它们明确包含在 Consumed.with 中并没有解决问题。
public static void runStreamFilter(String broker) throws Exception {
  final SensorMessageSerializer serializer = new SensorMessageSerializer();
  final SensorMessageDeserializer deserializer = new SensorMessageDeserializer();
  Properties props = new Properties();
  props.put(StreamsConfig.APPLICATION_ID_CONFIG, "stream-filter");
  props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, broker);
  props.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.Integer().getClass());
  props.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.serdeFrom(serializer, deserializer));

  final StreamsBuilder builder = new StreamsBuilder();

  final KStream<Integer, SensorMessage> input = builder.stream(KafkaConstants.TOPIC_IN, Consumed.with(Serdes.Integer(), Serdes.serdeFrom(serializer, deserializer)));
  final KStream<Integer, SensorMessage> output = input
    .filter((k,v) -> v.getValue() > 19)
    .groupByKey(Grouped.with(Serdes.Integer(), Serdes.serdeFrom(serializer, deserializer)))
    .windowedBy(TimeWindows.of(Duration.ofMillis(500)))
    .reduce((aggValue, newValue) -> avgReducer(aggValue, newValue))
    .mapValues(value -> latencyMapper(value))
    .toStream();


  output.to(KafkaConstants.TOPIC_OUT);

最佳答案

代码.windowedBy(TimeWindows.of(Duration.ofMillis(500))).reduce(..)返回 KTable<Windowed<K>, V>

为了将您的结果转换为 KStream<Integer, SensorMessage> ,您需要从 Windowed 对象中提取值,因此您需要在 toStream() 之后添加以下代码:
.map((key, value) -> KeyValue.pair(key.key(), value));

关于apache-kafka - toStream() 在窗口化 KTable 上不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56595340/

10-11 04:53