Flink-6.Flink 分組求和

package com.ctgu.flink.project;


import com.ctgu.flink.entity.BehaviorChannelCount;
import com.ctgu.flink.entity.MarketingUserBehavior;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.source.SourceFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.functions.windowing.WindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.SlidingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.sql.Timestamp;
import java.time.Duration;
import java.util.Arrays;
import java.util.List;
import java.util.Random;

public class Flink_Sql_Marketing {
    public static void main(String[] args) throws Exception {

        long start = System.currentTimeMillis();

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        DataStream<MarketingUserBehavior> dataStream = env.addSource(new SimulatedMarketingUserBehaviorSource())
                .assignTimestampsAndWatermarks(WatermarkStrategy
                        .<MarketingUserBehavior>forBoundedOutOfOrderness(Duration.ofSeconds(0))
                        .withTimestampAssigner((event, timestamp) -> event.getTimestamp()));

        dataStream.filter(data -> !"UNINSTALL".equals(data.getBehavior()))
                .keyBy(new KeySelector<MarketingUserBehavior, Tuple2<String, String>>() {

                    @Override
                    public Tuple2<String, String> getKey(MarketingUserBehavior userBehavior) throws Exception {
                        return new Tuple2<>(userBehavior.getChannel(), userBehavior.getBehavior());
                    }
                })
//                .keyBy(MarketingUserBehavior::getBehavior)
                .window(SlidingEventTimeWindows.of(Time.hours(1), Time.seconds(1)))
                .aggregate(new AverageAggregate(), new MyProcessWindowFunction())
                .print("分組求和:");

        dataStream.filter(data -> !"UNINSTALL".equals(data.getBehavior()))
                .map(new MyMapFunction())
                .keyBy(data -> data.f0)
                .window(SlidingEventTimeWindows.of(Time.hours(1), Time.seconds(1)))
                .aggregate(new AverageAggregate1(), new MyWindowFunction())
                .print("total:");

        env.execute("Table SQL");

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

    private static class SimulatedMarketingUserBehaviorSource implements SourceFunction<MarketingUserBehavior> {
        boolean running = true;
        List<String> behaviorList = Arrays.asList("CLICK", "DOWNLOAD", "INSTALL", "UNINSTALL");
        List<String> channelList = Arrays.asList("app store", "wechat", "tencent", "ali");
        Random rand = new Random();

        @Override
        public void run(SourceContext<MarketingUserBehavior> sourceContext) throws Exception {
            while (running) {
                long userId = rand.nextLong();
                String behavior = behaviorList.get(rand.nextInt(behaviorList.size()));
                String channel = channelList.get(rand.nextInt(channelList.size()));
                long timestamp = System.currentTimeMillis();
                MarketingUserBehavior userBehavior = new MarketingUserBehavior(userId, behavior, channel, timestamp);
                System.out.println(userBehavior);
                sourceContext.collect(userBehavior);
                Thread.sleep(100);
            }
        }

        @Override
        public void cancel() {
            running = false;
        }
    }

    private static class MyMapFunction extends RichMapFunction<MarketingUserBehavior, Tuple2<String, Long>> {

        @Override
        public Tuple2<String, Long> map(MarketingUserBehavior userBehavior) throws Exception {
            return new Tuple2<>("total", 1L);
        }
    }

    private static class AverageAggregate
            implements AggregateFunction<MarketingUserBehavior, Long, Long> {
        @Override
        public Long createAccumulator() {
            return 0L;
        }

        @Override
        public Long add(MarketingUserBehavior userBehavior, Long aLong) {
            return aLong + 1;
        }

        @Override
        public Long getResult(Long aLong) {
            return aLong;
        }

        @Override
        public Long merge(Long a, Long b) {
            return a + b;
        }
    }

    private static class AverageAggregate1
            implements AggregateFunction<Tuple2<String, Long>, Long, Long> {
        @Override
        public Long createAccumulator() {
            return 0L;
        }

        @Override
        public Long add(Tuple2<String, Long> tuple, Long aLong) {
            return aLong + 1;
        }

        @Override
        public Long getResult(Long aLong) {
            return aLong;
        }

        @Override
        public Long merge(Long a, Long b) {
            return a + b;
        }
    }

    private static class MyWindowFunction
            implements WindowFunction<Long, BehaviorChannelCount, String, TimeWindow> {

        @Override
        public void apply(String key,
                          TimeWindow timeWindow,
                          Iterable<Long> iterable,
                          Collector<BehaviorChannelCount> out) throws Exception {
            String windowEnd = new Timestamp(timeWindow.getEnd()).toString();
            Long count = iterable.iterator().next();
            out.collect(new BehaviorChannelCount(key, key, windowEnd, count));
        }
    }

    private static class MyProcessWindowFunction
            extends ProcessWindowFunction<Long, BehaviorChannelCount, Tuple2<String, String>, TimeWindow> {

        @Override
        public void process(Tuple2<String, String> tuple2,
                            Context context,
                            Iterable<Long> iterable,
                            Collector<BehaviorChannelCount> out) throws Exception {
            String channel = tuple2.getField(0);
            String behavior = tuple2.getField(1);
            String windowEnd = new Timestamp(context.window().getEnd()).toString();
            Long count = iterable.iterator().next();
            out.collect(new BehaviorChannelCount(behavior, channel, windowEnd, count));
        }
    }

}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末抑月,一起剝皮案震驚了整個濱河市树叽,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌谦絮,老刑警劉巖题诵,帶你破解...
    沈念sama閱讀 212,816評論 6 492
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件洁仗,死亡現(xiàn)場離奇詭異,居然都是意外死亡性锭,警方通過查閱死者的電腦和手機赠潦,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,729評論 3 385
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來草冈,“玉大人她奥,你說我怎么就攤上這事≡趵猓” “怎么了哩俭?”我有些...
    開封第一講書人閱讀 158,300評論 0 348
  • 文/不壞的土叔 我叫張陵,是天一觀的道長拳恋。 經(jīng)常有香客問我凡资,道長,這世上最難降的妖魔是什么谬运? 我笑而不...
    開封第一講書人閱讀 56,780評論 1 285
  • 正文 為了忘掉前任隙赁,我火速辦了婚禮,結(jié)果婚禮上吩谦,老公的妹妹穿的比我還像新娘鸳谜。我一直安慰自己,他們只是感情好式廷,可當我...
    茶點故事閱讀 65,890評論 6 385
  • 文/花漫 我一把揭開白布咐扭。 她就那樣靜靜地躺著,像睡著了一般滑废。 火紅的嫁衣襯著肌膚如雪蝗肪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 50,084評論 1 291
  • 那天蠕趁,我揣著相機與錄音薛闪,去河邊找鬼。 笑死俺陋,一個胖子當著我的面吹牛豁延,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播腊状,決...
    沈念sama閱讀 39,151評論 3 410
  • 文/蒼蘭香墨 我猛地睜開眼诱咏,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了缴挖?” 一聲冷哼從身側(cè)響起袋狞,我...
    開封第一講書人閱讀 37,912評論 0 268
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后苟鸯,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體同蜻,經(jīng)...
    沈念sama閱讀 44,355評論 1 303
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 36,666評論 2 327
  • 正文 我和宋清朗相戀三年早处,在試婚紗的時候發(fā)現(xiàn)自己被綠了湾蔓。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 38,809評論 1 341
  • 序言:一個原本活蹦亂跳的男人離奇死亡陕赃,死狀恐怖卵蛉,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情么库,我是刑警寧澤傻丝,帶...
    沈念sama閱讀 34,504評論 4 334
  • 正文 年R本政府宣布,位于F島的核電站诉儒,受9級特大地震影響葡缰,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜忱反,卻給世界環(huán)境...
    茶點故事閱讀 40,150評論 3 317
  • 文/蒙蒙 一泛释、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧温算,春花似錦怜校、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,882評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至巩割,卻和暖如春裙顽,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背宣谈。 一陣腳步聲響...
    開封第一講書人閱讀 32,121評論 1 267
  • 我被黑心中介騙來泰國打工愈犹, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人闻丑。 一個月前我還...
    沈念sama閱讀 46,628評論 2 362
  • 正文 我出身青樓漩怎,卻偏偏與公主長得像,于是被迫代替她去往敵國和親嗦嗡。 傳聞我的和親對象是個殘疾皇子扬卷,可洞房花燭夜當晚...
    茶點故事閱讀 43,724評論 2 351

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