37、Flink 的 WindowAssigner之会话窗口示例

1、处理时间

无需设置水位线和时间间隔。

bash 复制代码
input.keyBy(e -> e)
                .window(ProcessingTimeSessionWindows.withGap(Time.minutes(10)))
                .apply(new WindowFunction<String, String, String, TimeWindow>() {
                    @Override
                    public void apply(String s, TimeWindow timeWindow, Iterable<String> iterable, Collector<String> collector) throws Exception {
                        for (String string : iterable) {
                            collector.collect(string);
                        }
                    }
                })
                .print();

2、事件时间

需设置水位线和时间间隔。

bash 复制代码
// 事件时间需要设置水位线策略和时间戳
        SingleOutputStreamOperator<Tuple2<String, Long>> map = input.map(new MapFunction<String, Tuple2<String, Long>>() {
            @Override
            public Tuple2<String, Long> map(String input) throws Exception {
                String[] fields = input.split(",");
                return new Tuple2<>(fields[0], Long.parseLong(fields[1]));
            }
        });

        SingleOutputStreamOperator<Tuple2<String, Long>> watermarks = map.assignTimestampsAndWatermarks(WatermarkStrategy.<Tuple2<String, Long>>forBoundedOutOfOrderness(Duration.ofSeconds(0))
                .withTimestampAssigner(new SerializableTimestampAssigner<Tuple2<String, Long>>() {
                    @Override
                    public long extractTimestamp(Tuple2<String, Long> input, long l) {
                        return input.f1;
                    }
                }));

        // 设置了固定间隔的 event-time 会话窗口
        watermarks.keyBy(e -> e.f0)
                .window(EventTimeSessionWindows.withGap(Time.minutes(10)))
                .apply(new WindowFunction<Tuple2<String, Long>, String, String, TimeWindow>() {
                    @Override
                    public void apply(String s, TimeWindow timeWindow, Iterable<Tuple2<String, Long>> iterable, Collector<String> collector) throws Exception {
                        for (Tuple2<String, Long> stringLongTuple2 : iterable) {
                            collector.collect(stringLongTuple2.f0);
                        }
                    }
                })
                .print();

3、固定间隔和动态间隔

bash 复制代码
EventTimeSessionWindows.withGap(Time.minutes(10));

EventTimeSessionWindows.withDynamicGap(new SessionWindowTimeGapExtractor<Tuple2<String, Long>>() {
                    @Override
                    public long extract(Tuple2<String, Long> element) {
                        return element.f1 + 2000L;
                    }
                });

4、完整代码示例

bash 复制代码
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
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.windowing.WindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.EventTimeSessionWindows;
import org.apache.flink.streaming.api.windowing.assigners.ProcessingTimeSessionWindows;
import org.apache.flink.streaming.api.windowing.assigners.SessionWindowTimeGapExtractor;
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.time.Duration;

public class _04_WindowAssignerSession {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        DataStreamSource<String> input = env.socketTextStream("localhost", 8888);

        // 测试时限制了分区数,生产中需要设置空闲数据源
        env.setParallelism(2);

        // 事件时间需要设置水位线策略和时间戳
        SingleOutputStreamOperator<Tuple2<String, Long>> map = input.map(new MapFunction<String, Tuple2<String, Long>>() {
            @Override
            public Tuple2<String, Long> map(String input) throws Exception {
                String[] fields = input.split(",");
                return new Tuple2<>(fields[0], Long.parseLong(fields[1]));
            }
        });

        SingleOutputStreamOperator<Tuple2<String, Long>> watermarks = map.assignTimestampsAndWatermarks(WatermarkStrategy.<Tuple2<String, Long>>forBoundedOutOfOrderness(Duration.ofSeconds(0))
                .withTimestampAssigner(new SerializableTimestampAssigner<Tuple2<String, Long>>() {
                    @Override
                    public long extractTimestamp(Tuple2<String, Long> input, long l) {
                        return input.f1;
                    }
                }));

        // 设置了固定间隔的 event-time 会话窗口
        watermarks.keyBy(e -> e.f0)
                .window(EventTimeSessionWindows.withGap(Time.minutes(10)))
                .apply(new WindowFunction<Tuple2<String, Long>, String, String, TimeWindow>() {
                    @Override
                    public void apply(String s, TimeWindow timeWindow, Iterable<Tuple2<String, Long>> iterable, Collector<String> collector) throws Exception {
                        for (Tuple2<String, Long> stringLongTuple2 : iterable) {
                            collector.collect(stringLongTuple2.f0);
                        }
                    }
                })
                .print();

        // 设置了动态间隔的 event-time 会话窗口
        watermarks.keyBy(e -> e.f0)
                .window(EventTimeSessionWindows.withDynamicGap(new SessionWindowTimeGapExtractor<Tuple2<String, Long>>() {
                    @Override
                    public long extract(Tuple2<String, Long> element) {
                        return element.f1 + 2000L;
                    }
                }))
                .apply(new WindowFunction<Tuple2<String, Long>, String, String, TimeWindow>() {
                    @Override
                    public void apply(String s, TimeWindow timeWindow, Iterable<Tuple2<String, Long>> iterable, Collector<String> collector) throws Exception {
                        for (Tuple2<String, Long> stringLongTuple2 : iterable) {
                            collector.collect(stringLongTuple2.f0);
                        }
                    }
                })
                .print();

        // 设置了固定间隔的 processing-time session 窗口
        input.keyBy(e -> e)
                .window(ProcessingTimeSessionWindows.withGap(Time.minutes(10)))
                .apply(new WindowFunction<String, String, String, TimeWindow>() {
                    @Override
                    public void apply(String s, TimeWindow timeWindow, Iterable<String> iterable, Collector<String> collector) throws Exception {
                        for (String string : iterable) {
                            collector.collect(string);
                        }
                    }
                })
                .print();

        // 设置了动态间隔的 processing-time 会话窗口
        input.keyBy(e -> e)
                .window(ProcessingTimeSessionWindows.withDynamicGap(new SessionWindowTimeGapExtractor<String>() {
                    @Override
                    public long extract(String s) {
                        return System.currentTimeMillis() / 1000;
                    }
                }))
                .apply(new WindowFunction<String, String, String, TimeWindow>() {
                    @Override
                    public void apply(String s, TimeWindow timeWindow, Iterable<String> iterable, Collector<String> collector) throws Exception {
                        for (String string : iterable) {
                            collector.collect(string);
                        }
                    }
                })
                .print();

        env.execute();
    }
}
相关推荐
Hello.Reader3 小时前
Flink Checkpoint 通用调优方案三种画像 + 配置模板 + 容量估算 + 巡检脚本 + 告警阈值
大数据·flink
Hy行者勇哥6 小时前
公司全场景运营中 PPT 的类型、功能与作用详解
大数据·人工智能
liliangcsdn6 小时前
如何基于ElasticsearchRetriever构建RAG系统
大数据·elasticsearch·langchain
乐迪信息6 小时前
乐迪信息:基于AI算法的煤矿作业人员安全规范智能监测与预警系统
大数据·人工智能·算法·安全·视觉检测·推荐算法
极验6 小时前
iPhone17实体卡槽消失?eSIM 普及下的安全挑战与应对
大数据·运维·安全
B站_计算机毕业设计之家7 小时前
推荐系统实战:python新能源汽车智能推荐(两种协同过滤+Django 全栈项目 源码)计算机专业✅
大数据·python·django·汽车·推荐系统·新能源·新能源汽车
The Sheep 20237 小时前
WPF自定义路由事件
大数据·hadoop·wpf
SelectDB技术团队8 小时前
Apache Doris 内部数据裁剪与过滤机制的实现原理 | Deep Dive
大数据·数据库·apache·数据库系统·数据裁剪
WLJT1231231239 小时前
科技赋能塞上农业:宁夏从黄土地到绿硅谷的蝶变
大数据·人工智能·科技