我想编写一个小型的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);
答案 0 :(得分:4)
代码
.windowedBy(TimeWindows.of(Duration.ofMillis(500))).reduce(..)
返回KTable<Windowed<K>, V>
。
为了将结果转换为KStream<Integer, SensorMessage>
,需要从Windowed
对象中提取值,因此需要在toStream()
之后添加以下代码:
.map((key, value) -> KeyValue.pair(key.key(), value));