“ WindowedBy Count KStream”引发StreamsException

时间:2019-07-01 09:52:07

标签: spring count apache-kafka apache-kafka-streams

我试图将来自KStream的事件计数为时间段:

    KStream<String, VehicleEventTO> stream = builder.stream("vehicle", Consumed.with(Serdes.String(), new JsonSerde<>(VehicleEventTO.class)));

    KStream<String, VehicleEventTO> streamWithKey = stream.selectKey((key, value) -> value.getId_vehicle().toString());

    KStream<String, Long> streamValueKey = streamWithKey.map((key, value) -> KeyValue.pair(key, value.getId_vehicle()));

    streamValueKey.groupByKey()
                  .windowedBy(TimeWindows.of(Duration.ofMinutes(10).toMillis()))
                  .count(Materialized.with(Serdes.String(), new JsonSerde<>(Long.class)));

我有这个例外:

  

线程异常   “ test-app-87ce164d-c427-4dcf-aa76-aeeb6f8fc943-StreamThread-1”   org.apache.kafka.streams.errors.StreamsException:捕获了异常   处理。 taskId = 0_0,处理器= KSTREAM-SOURCE-0000000000,   主题=车辆,分区= 0,偏移= 160385,位于   org.apache.kafka.streams.processor.internals.StreamTask.process(StreamTask.java:318)     在   org.apache.kafka.streams.processor.internals.AssignedStreamsTasks.process(AssignedStreamsTasks.java:94)     在   org.apache.kafka.streams.processor.internals.TaskManager.process(TaskManager.java:409)     在   org.apache.kafka.streams.processor.internals.StreamThread.processAndMaybeCommit(StreamThread.java:964)     在   org.apache.kafka.streams.processor.internals.StreamThread.runOnce(StreamThread.java:832)     在   org.apache.kafka.streams.processor.internals.StreamThread.runLoop(StreamThread.java:767)     在   org.apache.kafka.streams.processor.internals.StreamThread.run(StreamThread.java:736)   引起原因:org.apache.kafka.streams.errors.StreamsException:A   序列化程序(键:   org.apache.kafka.common.serialization.ByteArraySerializer /值:   org.apache.kafka.common.serialization.ByteArraySerializer)不是   与实际的键或值类型兼容(键类型:java.lang.String   /值类型:java.lang.Long)。更改默认的Serdes in   StreamConfig或通过方法参数提供正确的Serdes。

1 个答案:

答案 0 :(得分:3)

groupByKey()使用默认的序列化器:

  

groupByKey()

     

按记录的当前键将记录分组为一个   KGroupedStream保留原始值和默认值   序列化器和反序列化器。

您必须使用groupByKey(Serialized<K,V> serialized)groupByKey(Grouped<K,V> grouped)

以下应该可以解决问题:

streamValueKey.groupByKey(Serialized.with(Serdes.String(), Serdes.Long()))
              .windowedBy(TimeWindows.of(Duration.ofMinutes(10).toMillis()))
              .count(Materialized.with(Serdes.String(), new JsonSerde<>(Long.class)));