Flink 利用KeyedProcessFunction处理数据超时没有流入问题

需求背景:当流超时没有数据流入,发出告警通知。

思路:

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()) { /
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值