Flink 计算 PV UV

前言

使用 flink 很长一段时间了,突然发现竟然没有计算过 pv uv,这可是 flink 常见的计算场景了,面试时也是常问题之一。故自己想了一个场景来计算一下。
基于 Flink 1.12

场景

外卖员听单的信息会发到单独一个 topic 中,计算一个每天有多少个 外卖员听单以及总共的听单次数。

kafka 中消息类型

{"locTime":"2020-12-28 12:32:23","courierId":12,"other":"aaa"}

locTime:事件发生的时间,courierId 外卖员id

计算一天有多少个外卖员听单( UV ),总共听单多少次( PV )

FlinkKafkaConsumer<String> consumer = new FlinkKafkaConsumer<String>(topics, new SimpleStringSchema(), properties);
        FlinkHelp.setOffset(parameter, consumer);
        consumer.assignTimestampsAndWatermarks(
                WatermarkStrategy.<String>forMonotonousTimestamps()
                        .withTimestampAssigner(new SerializableTimestampAssigner<String>() {
                            @Override
                            public long extractTimestamp(String element, long recordTimestamp) {
                                String locTime = "";
                                try {
                                    Map<String, Object> map = Json2Others.json2map(element);
                                    locTime = map.get("locTime").toString();
                                } catch (IOException e) {
                                }
                                LocalDateTime startDateTime =
                                        LocalDateTime.parse(locTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                                long milli = startDateTime.toInstant(OffsetDateTime.now().getOffset()).toEpochMilli();
                                return milli;
                            }
                        }).withIdleness(Duration.ofSeconds(1)));

        env.addSource(consumer).filter(new FilterFunction<String>() {
            @Override
            public boolean filter(String value) throws Exception {
                return true;
            }
        }).windowAll(TumblingEventTimeWindows.of(Time.days(1), Time.hours(-8)))
                .allowedLateness(Time.minutes(1))
//              .trigger(CountTrigger.of(5))// 其实多个 trigger 就是下一个 trigger 覆盖上一个 trigger
                //用 event time 可能会导致 window 延迟触发,最好的解决办法是在 processingTime 的基础上添加对窗口的判断
                // watermark 不会回退,所以如果消息早到的话( 乱序了,该相对来说晚到的消息早到了),可能会导致窗口延迟触发
                // 夸张一点的话,窗口不触发了,直到有大于等于 watermark + triggerTime 的消息到达
                // ContinuousProcessingTimeTrigger 一样
                .trigger(ContinuousEventTimeTrigger.of(Time.seconds(30)))
                //追历史数据的时候会有问题,可能历史数据不足 10s 就全部消费完毕,导致窗口不会被触发而被跳过,消费同理
//              .trigger(ContinuousProcessingTimeTrigger.of(Time.seconds(10)))
                //处理完毕后将 window state 中的数据清除掉
                // 其实完全可以通过自定义 trigger 来达到 clear windowState 的目的 (Purge)
                .evictor(TimeEvictor.of(Time.seconds(0), true))
                .process(new ProcessAllWindowFunction<String, String, TimeWindow>() {
                    private JedisCluster jedisCluster;
                    private MapState<String, String> courierInfoMapState;
                    private MapStateDescriptor<String, String> mapStateDescriptor;
                    private MapStateDescriptor<String, Long> mapStateUVDescriptor;
                    private MapState<String, Long> courierInfoUVMapState;
                    private MapStateDescriptor<String, Long> mapStatePVDescriptor;
                    private MapState<String, Long> courierInfoPVMapState;
                    private String beforeDay = "";
                    private String currentDay = "";

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        StateTtlConfig ttlConfig = StateTtlConfig
                                .newBuilder(org.apache.flink.api.common.time.Time.hours(25))
                                //default,不支持 eventTime 1.12.0
                                .setTtlTimeCharacteristic(StateTtlConfig.TtlTimeCharacteristic.ProcessingTime)
                                .cleanupInRocksdbCompactFilter(1000)
                                .setUpdateType(StateTtlConfig.UpdateType.OnCreateAndWrite)//default
                                .setStateVisibility(StateTtlConfig.StateVisibility.NeverReturnExpired)
                                .build();

                        mapStateDescriptor =
                                new MapStateDescriptor<String, String>("courierInfos", TypeInformation.of(String.class), TypeInformation.of(String.class));
                        mapStateDescriptor.enableTimeToLive(ttlConfig);
                        courierInfoMapState = getRuntimeContext().getMapState(mapStateDescriptor);

                        mapStateUVDescriptor =
                                new MapStateDescriptor<String, Long>("courierUVStateDesc", TypeInformation.of(String.class), TypeInformation.of(Long.class));
                        mapStateUVDescriptor.enableTimeToLive(ttlConfig);
                        courierInfoUVMapState = getRuntimeContext().getMapState(mapStateUVDescriptor);

                        mapStatePVDescriptor =
                                new MapStateDescriptor<String, Long>("courierPVStateDesc", TypeInformation.of(String.class), TypeInformation.of(Long.class));
                        mapStatePVDescriptor.enableTimeToLive(ttlConfig);
                        courierInfoPVMapState = getRuntimeContext().getMapState(mapStatePVDescriptor);


                        jedisCluster = RedisUtil.getJedisCluster(redisHp);
                    }

                    @Override
                    public void close() throws Exception {
                        RedisUtil.closeConn(jedisCluster);
                    }

                    @Override
                    public void process(Context context, Iterable<String> elements, Collector<String> out) throws Exception {
                        Iterator<String> iterator = elements.iterator();
                        TimeWindow window = context.window();
                        System.out.println(" window = "
                                + DateUtils.millisecondsToDateStr(window.getStart(), "yyyy-MM-dd HH:mm:ss")
                                + "-" + DateUtils.millisecondsToDateStr(window.getEnd(), "yyyy-MM-dd HH:mm:ss"));
                        while (iterator.hasNext()) {
                            Map<String, Object> map = Json2Others.json2map(iterator.next());
                            String courierId = map.get("courierId").toString();
                            String day = map.get("locTime").toString().split(" ")[0].replace("-", "");
                            if (courierInfoPVMapState.contains(day)) {
                                courierInfoPVMapState.put(day, courierInfoPVMapState.get(day) + 1);
                            } else {
                                courierInfoPVMapState.put(day, 1L);
                            }
                            if (!courierInfoMapState.contains(day + "-" + courierId)) {
                                if (courierInfoUVMapState.contains(day)) {
                                    courierInfoUVMapState.put(day, courierInfoUVMapState.get(day) + 1);
                                } else {
                                    courierInfoUVMapState.put(day, 1L);
                                }
                                courierInfoMapState.put(day + "-" + courierId, "");
                            }
                            currentDay = day;
                        }

                        HashMap<String, String> map = new HashMap<String, String>();
                        if (currentDay.equals(beforeDay)) {
                            map.put(currentDay + "-pv", courierInfoPVMapState.get(currentDay).toString());
                            map.put(currentDay + "-uv", courierInfoUVMapState.get(currentDay).toString());

                        } else {
                            map.put(currentDay + "-pv", courierInfoPVMapState.get(currentDay).toString());
                            map.put(currentDay + "-uv", courierInfoUVMapState.get(currentDay).toString());
                            //超过25个小时,昨天的数据就不对了
                            if (!beforeDay.isEmpty()) {
                                map.put(beforeDay + "-pv", courierInfoPVMapState.get(beforeDay).toString());
                                map.put(beforeDay + "-uv", courierInfoUVMapState.get(beforeDay).toString());
                            }
                        }
                        map.forEach((k, v) -> {
                            System.out.println(k + ":" + v);
                        });
                        jedisCluster.hmset("test_courier_puv:", map);
                        jedisCluster.expire("test_courier_puv:", 3 * 24 * 60 * 60);

                        beforeDay = currentDay;

                    }
                });

结果样例

20201227-pv:1111111
20201227-uv:111

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,425评论 4 361
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,058评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,186评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,848评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,249评论 3 286
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,554评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,830评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,536评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,239评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,505评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,004评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,346评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,999评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,060评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,821评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,574评论 2 271
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,480评论 2 267

推荐阅读更多精彩内容

  • 基于flink-1.8.1 本文转载自一文搞懂Flink内部的Exactly Once和At Least Once...
    李小李的路阅读 32,633评论 6 57
  • 转自:https://www.jianshu.com/p/4d31d6cddc99 如何理解flink中state...
    Jimmy2019阅读 373评论 0 0
  • 久违的晴天,家长会。 家长大会开好到教室时,离放学已经没多少时间了。班主任说已经安排了三个家长分享经验。 放学铃声...
    飘雪儿5阅读 7,401评论 16 21
  • 今天感恩节哎,感谢一直在我身边的亲朋好友。感恩相遇!感恩不离不弃。 中午开了第一次的党会,身份的转变要...
    迷月闪星情阅读 10,498评论 0 11
  • 可爱进取,孤独成精。努力飞翔,天堂翱翔。战争美好,孤独进取。胆大飞翔,成就辉煌。努力进取,遥望,和谐家园。可爱游走...
    赵原野阅读 2,681评论 1 1