使用 kafka 检测值的变化

Nik*_*ahu 5 stateful apache-kafka apache-kafka-streams

我有一个流应用程序,它不断接收坐标流以及一些还包括位串的自定义元数据。该流使用生产者 API 生成到 kafka 主题上。现在另一个应用程序需要处理此流 [Streams API] 并存储位字符串中的特定位,并在此位更改时生成警报

下面是需要处理的连续消息流

{"device_id":"1","status_bit":"0"}
{"device_id":"2","status_bit":"1"}
{"device_id":"1","status_bit":"0"}
{"device_id":"3","status_bit":"1"}
{"device_id":"1","status_bit":"1"} // need to generate alert with change: 0->1
{"device_id":"3","status_bits":"1"}
{"device_id":"2","status_bit":"1"}
{"device_id":"3","status_bits":"0"} // need to generate alert with change 1->0
Run Code Online (Sandbox Code Playgroud)

现在我想将这些警报写入另一个 kafka 主题,例如

{"device_id":1,"init":0,"final":1,"timestamp":"somets"}
{"device_id":3,"init":1,"final":0,"timestamp":"somets"}
Run Code Online (Sandbox Code Playgroud)

我可以使用类似的东西在状态存储中保存当前位

streamsBuilder
        .stream("my-topic")
        .mapValues((key, value) -> value.getStatusBit())
        .groupByKey()
        .windowedBy(TimeWindows.of(Duration.ofMinutes(1)))
        .reduce((oldAggValue, newMessageValue) -> newMessageValue, Materialized.as("bit-temp-store"));
Run Code Online (Sandbox Code Playgroud)

但我无法理解如何从现有位中检测到这种变化。我是否需要在处理器拓扑内部以某种方式查询状态存储?如果是?如何?如果不?还能做什么?

我可以尝试的任何建议/想法(可能与我的想法完全不同)也受到赞赏。我是 Kafka 的新手,我无法从事件驱动流的角度思考。

提前致谢。

Kat*_*ova 6

我不确定这是最好的方法,但在类似的任务中,我使用了一个中间实体来捕获状态变化。在您的情况下,它将类似于

    streamsBuilder.stream("my-topic").groupByKey()
              .aggregate(DeviceState::new, new Aggregator<String, Device, DeviceState>() {
            public DeviceState apply(String key, Device newValue, DeviceState state) {
                if(!newValue.getStatusBit().equals(state.getStatusBit())){
                     state.setChanged(true);    
                }
                state.setStatusBit(newValue.getStatusBit());
                state.setDeviceId(newValue.getDeviceId());
                state.setKey(key);
                return state;
            }
        }, TimeWindows.of(…) …).filter((s, t) -> (t.changed())).toStream();
Run Code Online (Sandbox Code Playgroud)

在生成的主题中,您将进行更改。你也可以给 DeviceState 添加一些属性来先初始化它,这取决于你是否要发送事件,第一个设备记录何时到达等。