美文网首页大数据Spark_Flink_Hadoop
使用Flink流处理完成实时数据比对(对账)四

使用Flink流处理完成实时数据比对(对账)四

作者: 李不言被占用了 | 来源:发表于2020-04-10 21:49 被阅读0次

    前面3篇文章使用Flink批处理完成数据比对(对账)三都是介绍Flink批处理的,有些业务场景可能需要实时对账,这个需要借助流处理来完成。

    流处理中connect方法可以将两个流合并在一起处理。

    流处理的业务场景需要考虑得比较多,因为数据是源源不断的产生的,当你拿到一方数据的时候,你需要思考多久后另一方数据流未到达就算超时呢?通俗一点讲,你从支付机构和银行同时获取数据,当你从支付机构获取到orderNo=1的数据的时候,等待多久后还没有从银行获取到orderNo=1的数据时,你就判断数据存在差异?一分钟、一小时、一天?这个需要读者自己去思考。

    但是flink要实现这样的业务场景非常简单,利用timerService和ValueState即可。当其中一方数据到达以后,将自己的数据保存,然后注册一个定时器,定时器到达后,判断对端数据还没到,则输出差异。

    在写代码前需要说明的是,Flink的时间概念很重要,Flink有三个时间:Event Time、Processing Time、Ingestion Time。如果读者已经了解了Flink,一定知道这几个时间的概念。不了解也没关系,简单说下Event Time,就是事件本身的时间,通俗点,就是数据自己携带的时间,如:

    orderId payMoney createTime
    order_1 11 2020-01-01 00:00:00
    order_2 22 2020-01-01 00:01:00
    order_3 33 2020-01-01 00:02:00

    这里,我们可以选取createTime作为我们的事件时间,那么对于order_1这条数据来说,它的数据事件时间就是2020-01-01 00:00:00,这就是数据自己携带的时间。

    编写代码

    说了这么多,还是直接看看代码吧:

    import com.flink.vo.BankVo;
    import com.flink.vo.DiffType;
    import com.flink.vo.MergeVo;
    import com.flink.vo.PayOrgVo;
    import org.apache.flink.api.common.state.ValueState;
    import org.apache.flink.api.common.state.ValueStateDescriptor;
    import org.apache.flink.configuration.Configuration;
    import org.apache.flink.streaming.api.TimeCharacteristic;
    import org.apache.flink.streaming.api.datastream.DataStreamSource;
    import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
    import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
    import org.apache.flink.streaming.api.functions.co.CoProcessFunction;
    import org.apache.flink.util.Collector;
    
    /**
     * Skeleton for a Flink Streaming Job.
     *
     * <p>For a tutorial how to write a Flink streaming application, check the
     * tutorials and examples on the <a href="http://flink.apache.org/docs/stable/">Flink Website</a>.
     *
     * <p>To package your application into a JAR file for execution, run
     * 'mvn clean package' on the command line.
     *
     * <p>If you change the name of the main class (with the public static void main(String[] args))
     * method, change the respective entry in the POM.xml file (simply search for 'mainClass').
     */
    public class StreamingJob {
    
        public static void main(String[] args) throws Exception {
            // set up the streaming execution environment
            final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
    
            // 将时间设置为Event Time
            env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime);
    
            DataStreamSource<PayOrgVo> source1 = env.fromElements(new PayOrgVo("113", 1), new PayOrgVo("000", 2), new PayOrgVo("115", 33));
            DataStreamSource<BankVo> source2 = env.fromElements(new BankVo("000", 2), new BankVo("115", 333), new BankVo("114", 4));
    
            SingleOutputStreamOperator<MergeVo> res = source1.connect(source2)
                    .keyBy(PayOrgVo::getOrderNo, BankVo::getOrderNo)
                    .process(new CoProcessFunction<PayOrgVo, BankVo, MergeVo>() {
    
                ValueState<PayOrgVo> payState;
                ValueState<BankVo> bankState;
                ValueState<Long> timerState;
    
                @Override
                public void open(Configuration parameters) throws Exception {
                    super.open(parameters);
                    payState = getRuntimeContext().getState(
                            new ValueStateDescriptor<PayOrgVo>("payState", PayOrgVo.class));
                    bankState = getRuntimeContext().getState(
                            new ValueStateDescriptor<BankVo>("bankState", BankVo.class));
                    timerState = getRuntimeContext().getState(
                            new ValueStateDescriptor<Long>("timerState", Long.class));
                }
    
                @Override
                public void processElement1(PayOrgVo value, Context ctx, Collector<MergeVo> out) throws Exception {
                    BankVo bankVo = bankState.value();// 看看银行端的数据是否到达
                    if (bankVo == null) {// 银行端的时间未到达
                        payState.update(value);// 将支付机构端的数据保存起来
                        long timer = value.getEventTime() + 10_000;// 获取到支付机构端时间的事件时间,加上10秒
                        // 注册一个定时器,即支付机构端的事件时间加10秒
                        ctx.timerService().registerEventTimeTimer(timer);
                        // 保存下这个时间,在deleteEventTimeTimer中需要
                        timerState.update(timer);
                    } else {
                        // 业务逻辑,不解释了
                        DiffType diffType = null;
                        if (value.getPayment().equals(bankVo.getPayment())) {
                            diffType = DiffType.F000;
                        } else {
                            diffType = DiffType.F115;
                        }
                        // 数据输出
                        out.collect(new MergeVo(diffType, value, bankVo));
    
                        // 两端的数据都到齐了,把定时器删掉,避免定时器被触发
                        // 至于deleteEventTimeTimer为什么需要传入刚才注册时的时间,看看源码就知道:
                        // org.apache.flink.streaming.api.operators.InternalTimerServiceImpl#deleteEventTimeTimer
                        // 里面调用了队列的remove方法,remove对象是TimerHeapInternalTimer
                        // 看看TimerHeapInternalTimer的equals方法知道
                        ctx.timerService().deleteEventTimeTimer(timerState.value());
                        // 清空状态
                        timerState.clear();
                    }
                }
    
                @Override
                public void processElement2(BankVo value, Context ctx, Collector<MergeVo> out) throws Exception {
                    // 跟processElement1逻辑一样
                    PayOrgVo payOrgVo = payState.value();
                    if (payOrgVo != null) {
                        DiffType diffType = null;
                        if (value.getPayment().equals(payOrgVo.getPayment())) {
                            diffType = DiffType.F000;
                        } else {
                            diffType = DiffType.F115;
                        }
                        out.collect(new MergeVo(diffType, payOrgVo, value));
                        ctx.timerService().deleteEventTimeTimer(timerState.value());
                        timerState.clear();
                    } else {
                        bankState.update(value);
                        long timer = value.getEventTime() + 10_000;
                        ctx.timerService().registerEventTimeTimer(timer);
                        timerState.update(timer);
                    }
                }
    
                @Override
                public void onTimer(long timestamp, OnTimerContext ctx, Collector<MergeVo> out) throws Exception {
                    // 定时器触发后,肯定有一端的数据在指定时间没有到达
                    PayOrgVo payOrgVo = payState.value();
                    BankVo bankVo = bankState.value();
                    DiffType diffType = null;
                    if (payOrgVo != null) {// 支付机构有数据,银行没有
                        diffType = DiffType.F113;
                    }
                    if (bankVo != null) {
                        diffType = DiffType.F114;
                    }
                    out.collect(new MergeVo(diffType, payOrgVo, bankVo));
    
                    // 清空状态数据
                    payState.clear();
                    bankState.clear();
                }
            });
    
            res.print();
            
    
            // 流处理需要自己显示调用,不然不会触发
            env.execute("Flink Streaming Java API Skeleton");
        }
    }
    

    代码里注释挺清楚了,如果未表达清楚的,留言交流吧。

    源码

    源码

    总结

    这几篇文章是自己刚学习时写的一些demo,暂时记录这么多,待后续深入学习后再完善。
    转载请注明出处

    相关文章

      网友评论

        本文标题:使用Flink流处理完成实时数据比对(对账)四

        本文链接:https://www.haomeiwen.com/subject/ktprmhtx.html