Flink-10.Flink 雙流join訂單對(duì)賬

package com.ctgu.flink.project;

import com.ctgu.flink.entity.OrderEvent;
import com.ctgu.flink.entity.ReceiptEvent;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
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.streaming.api.functions.co.ProcessJoinFunction;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.time.Duration;


public class Flink_Sql_Join {

    static OutputTag<OrderEvent> orderOutput = new OutputTag<OrderEvent>("unCompare Pay") {};
    static OutputTag<ReceiptEvent> receiptOutput = new OutputTag<ReceiptEvent>("unReceipt") {};

    public static void main(String[] args) throws Exception {
        long start = System.currentTimeMillis();
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        DataStream<OrderEvent> orderStream = env.readTextFile("data/OrderLog.csv")
                .filter(line -> line.split(",").length >= 4)
                .map(line -> {
                    String[] s = line.split(",");
                    return new OrderEvent(Long.valueOf(s[0]), s[1], s[2], Long.valueOf(s[3]) * 1000);
                })
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy.<OrderEvent>forBoundedOutOfOrderness(Duration.ZERO)
                                .withTimestampAssigner((event, timestamp) -> event.getTimestamp()))
                .filter(data -> !data.getTxId().equals(""));

        DataStream<ReceiptEvent> receiptStream = env.readTextFile("data/ReceiptLog.csv")
                .filter(line -> line.split(",").length >= 3)
                .map(line -> {
                    String[] s = line.split(",");
                    return new ReceiptEvent(s[0], s[1], Long.valueOf(s[2]) * 1000);
                })
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy.<ReceiptEvent>forBoundedOutOfOrderness(Duration.ZERO)
                                .withTimestampAssigner((event, timestamp) -> event.getTimestamp()));

        SingleOutputStreamOperator<Tuple2<OrderEvent, ReceiptEvent>> resultStream
                = orderStream.keyBy(OrderEvent::getTxId)
                .connect(receiptStream.keyBy(ReceiptEvent::getTxId))
                .process(new MyCoProcessFunction());

        resultStream.print("success");
        resultStream.getSideOutput(orderOutput).print("unPay");
        resultStream.getSideOutput(receiptOutput).print("unReceipt");

        orderStream.keyBy(OrderEvent::getTxId)
                .intervalJoin(receiptStream.keyBy(ReceiptEvent::getTxId))
                .between(Time.seconds(-30), Time.seconds(50))
                .process(new Flink_Sql_MatchByJoin.MyProcessJoinFunction()).print("success join");

        env.execute("Table SQL");

        System.out.println("耗時(shí): " + (System.currentTimeMillis() - start) / 1000);

    }

    public static class MyCoProcessFunction
            extends CoProcessFunction<OrderEvent, ReceiptEvent, Tuple2<OrderEvent, ReceiptEvent>> {

        ValueState<OrderEvent> payState;

        ValueState<ReceiptEvent> receiptState;

        @Override
        public void open(Configuration parameters) throws Exception {
            payState = getRuntimeContext().getState(new ValueStateDescriptor<>("pay", OrderEvent.class));
            receiptState = getRuntimeContext().getState(new ValueStateDescriptor<>("receipt", ReceiptEvent.class));
        }

        @Override
        public void processElement1(OrderEvent pay, Context context,
                                    Collector<Tuple2<OrderEvent, ReceiptEvent>> out) throws Exception {
            ReceiptEvent receipt = receiptState.value();
            if (receipt != null) {
                out.collect(new Tuple2<>(pay, receipt));
                payState.clear();
                receiptState.clear();
            } else {
                context.timerService().registerEventTimeTimer(pay.getTimestamp() + 5000);
                payState.update(pay);
            }
        }

        @Override
        public void processElement2(ReceiptEvent receipt, Context context,
                                    Collector<Tuple2<OrderEvent, ReceiptEvent>> out) throws Exception {
            OrderEvent pay = payState.value();
            if (pay != null) {
                out.collect(new Tuple2<>(pay, receipt));
                payState.clear();
                receiptState.clear();
            } else {
                context.timerService().registerEventTimeTimer(receipt.getTimestamp() + 3000);
                receiptState.update(receipt);
            }
        }

        @Override
        public void onTimer(long timestamp, OnTimerContext ctx, Collector<Tuple2<OrderEvent, ReceiptEvent>> out) throws Exception {
            if(payState.value() != null) {
                ctx.output(orderOutput, payState.value());
            }
            if(receiptState.value() != null) {
                ctx.output(receiptOutput, receiptState.value());
            }
            payState.clear();
            receiptState.clear();
        }
    }

    public static class MyProcessJoinFunction
            extends ProcessJoinFunction<OrderEvent, ReceiptEvent, Tuple2<OrderEvent, ReceiptEvent>> {

        @Override
        public void processElement(OrderEvent orderEvent, ReceiptEvent receiptEvent,
                                   Context context, Collector<Tuple2<OrderEvent, ReceiptEvent>> collector) throws Exception {
            collector.collect(new Tuple2<>(orderEvent, receiptEvent));
        }
    }

}

測(cè)試data

ewr342as4,wechat,1558430845
sd76f87d6,wechat,1558430847
3hu3k2432,alipay,1558430848
8fdsfae83,alipay,1558430850
32h3h4b4t,wechat,1558430852
766lk5nk4,wechat,1558430855
435kjb45d,alipay,1558430859
5k432k4n,wechat,1558430862
435kjb45s,wechat,1558430866
324jnd45s,wechat,1558430868
43jhin3k4,wechat,1558430871
98x0f8asd,alipay,1558430874
392094j32,wechat,1558430877
88df0wn92,alipay,1558430882
435kjb4432,alipay,1558430884
3hefw8jf,alipay,1558430885
499dfano2,wechat,1558430886
8xz09ddsaf,wechat,1558430889
3243hr9h9,wechat,1558430892
329d09f9f,alipay,1558430893
809saf0ff,wechat,1558430895
324n0239,wechat,1558430899
sad90df3,alipay,1558430901
24309dsf,alipay,1558430902
rnp435rk,wechat,1558430905
8c6vs8dd,wechat,1558430906
3245nbo7,alipay,1558430908
8x0zvy8w3,alipay,1558430911
9032n4fd2,wechat,1558430913
d8938034,wechat,1558430915
32499fd9w,alipay,1558430921
9203kmfn,alipay,1558430922
390mf2398,alipay,1558430926
902dsqw45,wechat,1558430927
84309dw31r,alipay,1558430933
sddf9809ew,alipay,1558430936
832jksmd9,wechat,1558430938
m23sare32e,wechat,1558430940
92nr903msa,wechat,1558430944
sdafen9932,alipay,1558430949
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末迅皇,一起剝皮案震驚了整個(gè)濱河市螟蝙,隨后出現(xiàn)的幾起案子携冤,更是在濱河造成了極大的恐慌灯节,老刑警劉巖抹竹,帶你破解...
    沈念sama閱讀 212,816評(píng)論 6 492
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異卡啰,居然都是意外死亡趁俊,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,729評(píng)論 3 385
  • 文/潘曉璐 我一進(jìn)店門(mén)放椰,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)作烟,“玉大人,你說(shuō)我怎么就攤上這事砾医∧昧茫” “怎么了?”我有些...
    開(kāi)封第一講書(shū)人閱讀 158,300評(píng)論 0 348
  • 文/不壞的土叔 我叫張陵如蚜,是天一觀的道長(zhǎng)压恒。 經(jīng)常有香客問(wèn)我,道長(zhǎng)错邦,這世上最難降的妖魔是什么探赫? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 56,780評(píng)論 1 285
  • 正文 為了忘掉前任,我火速辦了婚禮撬呢,結(jié)果婚禮上伦吠,老公的妹妹穿的比我還像新娘。我一直安慰自己魂拦,他們只是感情好毛仪,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,890評(píng)論 6 385
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著芯勘,像睡著了一般潭千。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上借尿,一...
    開(kāi)封第一講書(shū)人閱讀 50,084評(píng)論 1 291
  • 那天刨晴,我揣著相機(jī)與錄音,去河邊找鬼路翻。 笑死狈癞,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的茂契。 我是一名探鬼主播蝶桶,決...
    沈念sama閱讀 39,151評(píng)論 3 410
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼掉冶!你這毒婦竟也來(lái)了真竖?” 一聲冷哼從身側(cè)響起脐雪,我...
    開(kāi)封第一講書(shū)人閱讀 37,912評(píng)論 0 268
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎恢共,沒(méi)想到半個(gè)月后战秋,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 44,355評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡讨韭,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,666評(píng)論 2 327
  • 正文 我和宋清朗相戀三年脂信,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片透硝。...
    茶點(diǎn)故事閱讀 38,809評(píng)論 1 341
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡狰闪,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出濒生,到底是詐尸還是另有隱情埋泵,我是刑警寧澤,帶...
    沈念sama閱讀 34,504評(píng)論 4 334
  • 正文 年R本政府宣布罪治,位于F島的核電站秋泄,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏规阀。R本人自食惡果不足惜恒序,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 40,150評(píng)論 3 317
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望谁撼。 院中可真熱鬧歧胁,春花似錦、人聲如沸厉碟。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 30,882評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)箍鼓。三九已至崭参,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間款咖,已是汗流浹背何暮。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 32,121評(píng)論 1 267
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留铐殃,地道東北人海洼。 一個(gè)月前我還...
    沈念sama閱讀 46,628評(píng)論 2 362
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像富腊,于是被迫代替她去往敵國(guó)和親坏逢。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,724評(píng)論 2 351

推薦閱讀更多精彩內(nèi)容