35、Flink 的 WindowAssigner之滚动窗口示例

1、处理时间

无须设置水位线策略和时间戳分配。

bash 复制代码
input.keyBy(e -> e)
                .window(TumblingProcessingTimeWindows.of(Duration.ofSeconds(5)))
                .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 复制代码
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;
                    }
                }));
                
		watermarks.keyBy(e -> e.f0)
                .window(TumblingEventTimeWindows.of(Duration.ofSeconds(5)))
                .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> input : iterable) {
                            collector.collect(input.f0);
                        }
                    }
                })
                .print();
相关推荐
lifewange6 分钟前
Hadoop 全套常用 Shell 命令完整版
大数据·hadoop·npm
乐观勇敢坚强的老彭6 分钟前
C++信奥洛谷循环章节练习题
java·c++·算法
菜菜小狗的学习笔记8 分钟前
八股(八)Maven、Git、Docker
java·maven
他是龙5519 分钟前
66:Java安全&SPEL表达式&SSTI模版注入&XXE&JDBC&MyBatis注入
java·安全·mybatis
一路向北North12 分钟前
Spring Security OAuth2.0(13):oAuth2.0微服务解析
java·spring·微服务
人道领域13 分钟前
【LeetCode刷题日记】119.最长连续序列(字节面试题最新)
java·算法·leetcode·面试·职场和发展
renhongxia115 分钟前
从内部进行大型语言模型安全
大数据·人工智能·安全·语言模型·自然语言处理·逻辑回归
大G的笔记本16 分钟前
redis常用场景-java示例
java·开发语言·redis
成为你的宁宁18 分钟前
【Kubernetes Secret 安全配置指南:从创建配置到环境变量、数据卷使用及私有镜像仓库实践】
java·安全·kubernetes
xieliyu.18 分钟前
Java手搓数据结构:从零模拟实现顺序表增删改查
java·开发语言·数据结构·学习·顺序表