《动手学Flink》——Window

Windows是处理无限流的核心。Windows将流分成有限大小的“存储桶”
窗口式Flink程序的一般结构如下所示。第一个片段是指键控流,而第二个片段是指非键控流。可以看到,唯一的区别是对键控流的keyBy(…)调用和对非键控流的window(…)变为windowAll(…)。这还将用作本页面其余部分的路线图。
在这里插入图片描述
在上面,方括号([…])中的命令是可选的。这表明Flink允许您以多种不同方式自定义窗口逻辑,从而使其最适合您的需求。

Window 类型

Window 类型可以分成两类:

  • CountWindow:按照指定的数据条数生成一个Window,与时间无关。
  • TimeWindow:按照时间生成Window。
    对于TimeWindow,可以根据窗口实现原理的不同分成三类:滚动窗口(Tumbling Window)、滑动窗口(Sliding Window)、和会话窗口(Session Window)。

1. 滚动窗口(Tumbling Windows)
将数据依据固定的窗口长度对数据进行切片。
特点 :时间对齐, 窗口长度 固定,没有重 叠。
滚动窗口分配器将每个元素分配到一个指定窗口大小的窗口中,滚动窗口有一个固定的大小,并且不会出现重叠。例如:如果你指定了一个 5 分钟大小的滚动窗口,窗口的创建如下图所示:在这里插入图片描述
适用场景:适合做 BI 统计等(做每个时间段的聚合计算)。
2. 滑动窗口(Sliding Windows)
滑动窗口是固定窗口的更广义的一种形式,滑动窗口由固定的窗口长度和滑动间隔组成。
特点 :时间对齐, 窗口长度 固定, 可以有 重叠。
滑动窗口分配器将元素分配到固定长度的窗口中,与滚动窗口类似,窗口的大小由窗口大小参数来配置,另一个窗口滑动参数控制滑动窗口开始的频率。因此,滑动窗口如果滑动参数小于窗口大小的话,窗口是可以重叠的,在这种情况下元素会被分配到多个窗口中。
例如,你有 10 分钟的窗口和 5 分钟的滑动,那么每个窗口中 5 分钟的窗口里包含着上个 10 分钟产生的数据,如下图所示:
在这里插入图片描述
适用场景:对最近一个时间段内的统计(求某接口最近 5min 的失败率来决定是否要报警)。
3. 会话窗口(Session Windows)
由一系列事件组合一个指定时间长度的 timeout 间隙组成,类似于 web 应用的session,也就是一段时间没有接收到新数据就会生成新的窗口。
特点 :时间无对齐 。
session 窗口分配器通过 session 活动来对元素进行分组,session 窗口跟滚动窗口和滑动窗口相比,不会有重叠和固定的开始时间和结束时间的情况,相反,当它在一个固定的时间周期内不再收到元素,即非活动间隔产生,那个这个窗口就会关闭。一个 session 窗口通过一个 session 间隔来配置,这个 session 间隔定义了非活跃周期的长度,当这个非活跃周期产生,那么当前的 session 将关闭并且后续的元素将被分配到新的 session 窗口中去。
在这里插入图片描述

Window API

TimeWindow() :

是将指定时间范围内的所有数据组成一个 window,一次对一个window 里面的所有数据进行计算。

1. 滚动窗口

  • Flink 默认的时间窗口根据 Processing Time 进行 窗口的划分,将 Flink 获取到的数据根据进入 Flink
    的时间划分到不同的窗口中。
  • 时间间隔可以通过 Time.milliseconds(x),Time.seconds(x),Time.minutes(x)等其中的一个来指定。
package com.hadwinling.apitest.c04_window;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.TimeCharacteristic;
import org.apache.flink.streaming.api.datastream.*;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;


/**
 * @description: timeWindow 分组后,每一个组5秒收集数据才会触发窗口执行
 * @author: hadwinling
 * @time: 2021/3/30 上午9:26
 */
public class C04_TimeWindow {
    public static void main(String[] args) throws Exception {
        //1. 创建环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setStreamTimeCharacteristic(TimeCharacteristic.ProcessingTime);
        // spark,3
        // hadoop,2
        DataStreamSource<String> lines = env.socketTextStream("localhost", 7777);

        SingleOutputStreamOperator<Tuple2<String, Integer>> wordAndCount = lines.map(new MapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public Tuple2<String, Integer> map(String s) throws Exception {
                String[] split = s.split(",");
                String word = split[0];
                int count = Integer.parseInt(split[1]);
                return Tuple2.of(word, count);
            }
        });

        // 先分组,在划分窗口
        KeyedStream<Tuple2<String, Integer>, Tuple> keyed = wordAndCount.keyBy(0);

        // 划分滚动窗口timeWindow,只传入一个参数
        WindowedStream<Tuple2<String, Integer>, Tuple, TimeWindow> tuple2TupleTimeWindowWindowedStream = keyed.timeWindow(Time.seconds(5));

        SingleOutputStreamOperator<Tuple2<String, Integer>> sum = tuple2TupleTimeWindowWindowedStream.sum(1);

        sum.print();

        env.execute();
    }
}

2. 滑动窗口(SlidingEventTimeWindows)

  • 滑动窗口和滚动窗口的函数名是完全一致的,只是在传参数时需要传入两个参数,一个是 window_size,一个是 sliding_size。
  • 时间间隔可以通过 Time.milliseconds(x),Time.seconds(x),Time.minutes(x)等其中的一个来指定。
  • 下面代码中的 sliding_size 设置为了 5s,也就是说,每 5s 就计算输出结果一次,每一次计算的 window 范围是 10s
    内的所有元素。
package com.hadwinling.apitest.c04_window;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.TimeCharacteristic;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.datastream.WindowedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;

/**
 * @description: 分组后再调用SlidingWindow,通常来算趋势(有重叠)
 * @author: hadwinling
 * @time: 2021/3/30 上午9:51
 */
public class C06_SlidingWindow {
    public static void main(String[] args) throws Exception {
        //1.
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        env.setStreamTimeCharacteristic(TimeCharacteristic.ProcessingTime);

        //spark ,2
        //hadoop,3
        DataStreamSource<String> lines = env.socketTextStream("localhost", 7777);

        SingleOutputStreamOperator<Tuple2<String, Integer>> map = lines.map(new MapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public Tuple2<String, Integer> map(String s) throws Exception {
                String[] split = s.split(",");
                String word = split[0];
                int count = Integer.parseInt(split[1]);
                return Tuple2.of(word, count);
            }
        });

        // 先分组,在划分窗口
        KeyedStream<Tuple2<String, Integer>, Tuple> tuple2TupleKeyedStream = map.keyBy(0);

        // 划分窗口
        WindowedStream<Tuple2<String, Integer>, Tuple, TimeWindow> tuple2TupleTimeWindowWindowedStream = tuple2TupleKeyedStream.timeWindow(Time.seconds(10), Time.seconds(5));

        SingleOutputStreamOperator<Tuple2<String, Integer>> sum = tuple2TupleTimeWindowWindowedStream.sum(1);

        sum.print();

        env.execute();
    }
}

会话窗口(Session Window)

注意由于会话窗口没有固定的开始和结束,因此对它们的评估与滚动窗口和滑动窗口的评估方法不同。在内部,会话窗口运算符会为每个到达的记录创建一个新窗口,如果窗口彼此之间的距离比已定义的间隔更近,则将它们合并在一起。为了可合并的,会话窗口操作者需要一个合并触发器以及合并的窗函数,如ReduceFunction,AggregateFunction或ProcessWindowFunction

package com.hadwinling.apitest.c04_window;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.TimeCharacteristic;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.datastream.WindowedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.assigners.ProcessingTimeSessionWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;

/**
 * @description: 距离上一次会话时间超过时间,触发
 * @author: hadwinling
 * @time: 2021/3/30 上午9:57
 */
public class C07_SeesionWindow {
    public static void main(String[] args) throws Exception {
        //
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setStreamTimeCharacteristic(TimeCharacteristic.ProcessingTime);
        env.setParallelism(1);

        // spark,3
        // hadoop,2
        DataStreamSource<String> lines = env.socketTextStream("localhost", 7777);

        SingleOutputStreamOperator<Tuple2<String, Integer>> wordAndCount = lines.map(new MapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public Tuple2<String, Integer> map(String value) throws Exception {
                String[] fields = value.split(",");
                String word = fields[0];
                Integer count = Integer.parseInt(fields[1]);
                return Tuple2.of(word, count);
            }
        });

        // 先分组,再划分窗口
        KeyedStream<Tuple2<String, Integer>, Tuple> keyed = wordAndCount.keyBy(0);

        // 划分窗口
        WindowedStream<Tuple2<String, Integer>, Tuple, TimeWindow> window = keyed.window(ProcessingTimeSessionWindows.withGap(Time.seconds(5)));

        SingleOutputStreamOperator<Tuple2<String, Integer>> summed = window.sum(1);

        summed.print();

        env.execute();
    }
}

CountWindow():

根据窗口中相同 key 元素的数量来触发执行,执行时只计算元素数量达到窗口大小的 key 对应的结果。

注意:CountWindow 的 window_size 指的是相同 Key 的元素的个数,不是输入的所有元素的总数。

滚动窗口:默认的 CountWindow 是一个滚动窗口,只需要指定窗口大小即可,当元素数量达到窗口大小时,就会触发窗口的执行。

package com.hadwinling.apitest.c04_window;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.datastream.WindowedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.windows.GlobalWindow;

/**
 * @description:  分组后再调用CountWindow,每一个组达到一定的条数才会触发窗口执行
 * @author: hadwinling
 * @time: 2021/3/30 上午9:14
 */
public class C02_CountWindow {
    public static void main(String[] args) throws Exception {
        // 1.
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        // 输入形式如下:
        // spark,3
        // hadoop,2
        DataStreamSource<String> lines = env.socketTextStream("localhost", 7777);

        SingleOutputStreamOperator<Tuple2<String, Integer>> wordAndCount = lines.map(new MapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public Tuple2<String, Integer> map(String s) throws Exception {
                String[] fields = s.split(",");
                String word = fields[0];
                Integer count = Integer.parseInt(fields[1]);
                return Tuple2.of(word, count);
            }
        });

        // 先分组,再划分窗口
        KeyedStream<Tuple2<String, Integer>, Tuple> tuple2TupleKeyedStream = wordAndCount.keyBy(0);

        // 划分窗口
        WindowedStream<Tuple2<String, Integer>, Tuple, GlobalWindow> tuple2TupleGlobalWindowWindowedStream = tuple2TupleKeyedStream.countWindow(5);

        SingleOutputStreamOperator<Tuple2<String, Integer>> sum = tuple2TupleGlobalWindowWindowedStream.sum(1);

        sum.print();

        env.execute();
    }
}

滑动窗口:滑动窗口和滚动窗口的函数名是完全一致的,只是在传参数时需要传入两个参数,一个是 window_size,一个是 sliding_size。

下面代码中的 sliding_size 设置为了 2,也就是说,每收到两个相同 key 的数据就计算一次,每一次计算的 window 范围是 10 个元素。

package com.hadwinling.apitest.c04_window;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.datastream.WindowedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.windows.GlobalWindow;

/**
 * @description:  分组后再调用CountWindow,每一个组达到一定的条数才会触发窗口执行
 * @author: hadwinling
 * @time: 2021/3/30 上午9:14
 */
public class C02_CountWindow {
    public static void main(String[] args) throws Exception {
        // 1.
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        // 输入形式如下:
        // spark,3
        // hadoop,2
        DataStreamSource<String> lines = env.socketTextStream("localhost", 7777);

        SingleOutputStreamOperator<Tuple2<String, Integer>> wordAndCount = lines.map(new MapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public Tuple2<String, Integer> map(String s) throws Exception {
                String[] fields = s.split(",");
                String word = fields[0];
                Integer count = Integer.parseInt(fields[1]);
                return Tuple2.of(word, count);
            }
        });

        // 先分组,再划分窗口
        KeyedStream<Tuple2<String, Integer>, Tuple> tuple2TupleKeyedStream = wordAndCount.keyBy(0);

        // 划分窗口
        WindowedStream<Tuple2<String, Integer>, Tuple, GlobalWindow> tuple2TupleGlobalWindowWindowedStream = tuple2TupleKeyedStream.countWindow(105);

        SingleOutputStreamOperator<Tuple2<String, Integer>> sum = tuple2TupleGlobalWindowWindowedStream.sum(1);

        sum.print();

        env.execute();
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值