Flink流处理Window API之窗口函数

接上篇Flink中流处理之Window,上节中我们提到了可以为窗口设置滚动窗口,滑动窗口等,在设置后其实不能就这样结束了,我们还需要在窗口中指定如何计算,从而引入了窗口函数的概念,一旦窗口关闭, window function 去计算处理窗口中的每个元素.

window function 定义了要对窗口中收集的数据做的计算操作,主要可以分为两类(注意在使用窗口函数之前一定需要KeyBy分组):

  • 增量聚合函数
    每条数据到来就进行计算,保持一个简单的状态。典型的增量聚合函数有ReduceFunction, AggregateFunction

  • 全窗口函数
    先把窗口所有数据收集起来,等到计算的时候会遍历所有数据。ProcessWindowFunction就是一个全窗口函数。

其中ReduceFunction,AggregateFunction更加高效, 原因就是Flink可以对到来的元素进行增量聚合,而ProcessWindowFunction不能被高效执行的原因是Flink在执行这个函数之前, 需要在内部缓存这个窗口上所有的元素。

下面为使用增量聚合函数ReduceFunction演示WordCount

import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
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.assigners.TumblingProcessingTimeWindows;
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.util.HashMap;

public class Flink_Window_TimeTumbling_ReduceFunction
{

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

        //1.获取流处理时的执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        //2.读取socket数据流
        DataStreamSource<String> inputFile = env.socketTextStream("mo",8888);

        //3. 进行FlatMap操作转换成元祖
        SingleOutputStreamOperator<Tuple2<String, Integer>> WordTOWordOne = inputFile.flatMap(new MyFlatMapFunction());

        //4.进行分组
        KeyedStream<Tuple2<String, Integer>, String> keyedStream = WordTOWordOne.keyBy(x->x.f0);

        //5.开启一个5s的滑动窗口
        WindowedStream<Tuple2<String, Integer>, String, TimeWindow> window = keyedStream.window(TumblingProcessingTimeWindows.of(Time.seconds(5)));

        //5.进行窗口的聚合操作,window的增量聚合函数包含ReduceFunction 和 AggregateFunction
        // 这里使用的是WindowsFunc中的ReduceFunction,也可以使用之前的sum简单操作
        SingleOutputStreamOperator<Tuple2<String, Integer>> res = window.reduce(new ReduceFunction<Tuple2<String, Integer>>() {
            @Override
            public Tuple2<String, Integer> reduce(Tuple2<String, Integer> value1, Tuple2<String, Integer> value2) throws Exception {
                return new Tuple2<>(value1.f0, value1.f1 + value2.f1);
            }
        });

        res.print();

        env.execute("Window_TimeTumbling");
    }

    //将单词转为(word,one)的形式
    public static class MyFlatMapFunction implements FlatMapFunction<String,Tuple2<String,Integer>> {
        @Override
        public void flatMap(String value, Collector<Tuple2<String, Integer>> out) throws Exception {
            String[] words = value.split(" ");
            for (String word : words) {
                out.collect(new Tuple2<String, Integer>(word,1));
            }
        }
    }


}

在这里插入图片描述
其中窗口的大小为5s,此时第5步的聚合操作也可以换为AggregateFunction。

SingleOutputStreamOperator<Tuple2<String, Integer>> res = window.aggregate(new AggregateFunction<Tuple2<String, Integer>, Tuple2<String, Integer>, Tuple2<String, Integer>>() {
            @Override
            //创建一个中间过程的累加器,并赋初始值
            public Tuple2<String, Integer> createAccumulator() {
                return new Tuple2<>("", 0);
            }

            @Override
            //累加器的操作,key用的是传入新数据的f0,value为传入新数据的f1 + 累加器的f1
            public Tuple2<String, Integer> add(Tuple2<String, Integer> value, Tuple2<String, Integer> accumulator) {
                return new Tuple2<>(value.f0, value.f1 + accumulator.f1);
            }

            //获取累加器的值
            @Override
            public Tuple2<String, Integer> getResult(Tuple2<String, Integer> accumulator) {
                return new Tuple2<>(accumulator.f0, accumulator.f1);
            }

            //累加器的合并: 只有会话窗口才会调用
            @Override
            public Tuple2<String, Integer> merge(Tuple2<String, Integer> a, Tuple2<String, Integer> b) {
                return null;
            }
        });
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值