gpt4 book ai didi

timer - Apache Flink - 如果 x 分钟没有收到数据,则发送事件

转载 作者:行者123 更新时间:2023-12-03 13:46:06 26 4
gpt4 key购买 nike

如何使用 Flink 的 DataStream API 实现一个运算符,该运算符在一段时间内未从流中接收到数据时发送事件?

最佳答案

这样的操作符可以使用 ProcessFunction 来实现。 .

DataStream<Long> input = env.fromElements(1L, 2L, 3L, 4L);

input
// use keyBy to have keyed state.
// NullByteKeySelector will move all data to one task. You can also use other keys
.keyBy(new NullByteKeySelector())
// use process function with 60 seconds timeout
.process(new TimeOutFunction(60 * 1000));
TimeOutFunction定义如下。在本例中,它使用处理时间。

public static class TimeOutFunction extends ProcessFunction<Long, Boolean> {

// delay after which an alert flag is thrown
private final long timeOut;
// state to remember the last timer set
private transient ValueState<Long> lastTimer;

public TimeOutFunction(long timeOut) {
this.timeOut = timeOut;
}

@Override
public void open(Configuration conf) {
// setup timer state
ValueStateDescriptor<Long> lastTimerDesc =
new ValueStateDescriptor<Long>("lastTimer", Long.class);
lastTimer = getRuntimeContext().getState(lastTimerDesc);
}

@Override
public void processElement(Long value, Context ctx, Collector<Boolean> out) throws Exception {
// get current time and compute timeout time
long currentTime = ctx.timerService().currentProcessingTime();
long timeoutTime = currentTime + timeOut;
// register timer for timeout time
ctx.timerService().registerProcessingTimeTimer(timeoutTime);
// remember timeout time
lastTimer.update(timeoutTime);
}

@Override
public void onTimer(long timestamp, OnTimerContext ctx, Collector<Boolean> out) throws Exception {
// check if this was the last timer we registered
if (timestamp == lastTimer.value()) {
// it was, so no data was received afterwards.
// fire an alert.
out.collect(true);
}
}
}

关于timer - Apache Flink - 如果 x 分钟没有收到数据,则发送事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47059762/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com