需求背景:当流超时没有数据流入,发出告警通知。
思路:
KeyedProcessFunction中有onTimer()方法,将时间注册到timerService中,在指定时间触发onTimer()方法,在onTimer()中结合State判断是否超时。
class TimeoutFunction extends KeyedProcessFunction<Tuple, Event, Event> {
private final long timeout;
private transient ValueState<Long> lastTimer;
private final OutputTag<Alert> sideOutput;
public TimeoutFunction(long timeout, OutputTag<Alert> sideOutput) {
this.timeout = timeout;
this.sideOutput = sideOutput;
}
@Override
public void open(Configuration params) throws Exception {
super.open(params);
ValueStateDescriptor<Long> lastTimerDesc = new ValueStateDescriptor<>("lastTimer", Long.class);
lastTimer = getRuntime().getState(lastTimerDesc);
}
@Override
public void processElement(Event event, Context ctx, Collector<Event> collector) throws Exception {
long current = ctx.timerService().currenProcessingTime();
long nextTimeout = current + timeout;
ctx.timerService().registerProcessingTimeTimer(nextTimeout); // 注册Timer
lastTimer.update(nextTimeout); // 记录超时时间
}
@Override
public void onTimer(long ts, OnTimerContext ctx, Collector<Event> out) throws Exception {
String id = ctx.getCurrentKey().getField(0);
if (ts == lastTimer.value()) { /