Flink之函数使用

1. WindowFunction

在滚动窗口中使用 WindowFunction 函数来实现对数据的统计。

样例数据:

9,3
9,2
9,7
4,9
2,6

import org.apache.flink.api.common.functions.MapFunction;
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.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.ProcessingTimeSessionWindows;
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;

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

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        DataStreamSource<String> source = env.socketTextStream("192.168.88.161", 9999);
        source.setParallelism(1);
        SingleOutputStreamOperator<Tuple2<Integer, Integer>> mapData = source.map(new MapFunction<String, Tuple2<Integer, Integer>>() {
            @Override
            public Tuple2<Integer, Integer> map(String value) throws Exception {
                String[] arr = value.split(",");
                return Tuple2.of(Integer.valueOf(arr[0]), Integer.valueOf(arr[1]));
            }
        });
        mapData.keyBy(line->line.f0)
//                todo 滚动窗口 每三秒一计算
                .window(TumblingProcessingTimeWindows.of(Time.seconds(3)))
                .apply(new WindowFunction<Tuple2<Integer, Integer>, Tuple2<Integer, Integer>, Integer, TimeWindow>() {
                    @Override
                    public void apply(Integer integer, TimeWindow window, Iterable<Tuple2<Integer, Integer>> input, Collector<Tuple2<Integer, Integer>> out) throws Exception {
                        Integer key = 0;
                        Integer count = 0;
                        for (Tuple2<Integer, Integer> line : input){
//                          key 获取的是 参数
                            key = line.f0;
//                          count 获取的是对指定参数进行累加操作
                            count += line.f1;
                        }
                        out.collect(Tuple2.of(key,count));
                    }
                })
                .print();
        env.execute();
    }
}

给程序开一个单独的端口:nc -lk 9999

当程序运行后,在开的端口处发送数据并在控制台打印输出结果:

2. ReduceFunction

在滑动窗口之使用 ReduceFunction 实现对数据的统计并输出。

样例数据:

9,3
9,2
9,7
4,9
2,6
1,5
2,3
5,7
5,4

import org.apache.flink.api.common.functions.MapFunction;
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.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.ProcessingTimeSessionWindows;
import org.apache.flink.streaming.api.windowing.assigners.SlidingProcessingTimeWindows;
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;

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

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        DataStreamSource<String> source = env.socketTextStream("192.168.88.161", 9999);
        source.setParallelism(1);
        SingleOutputStreamOperator<Tuple2<Integer, Integer>> mapData = source.map(new MapFunction<String, Tuple2<Integer, Integer>>() {
            @Override
            public Tuple2<Integer, Integer> map(String value) throws Exception {
                String[] arr = value.split(",");
                return Tuple2.of(Integer.valueOf(arr[0]), Integer.valueOf(arr[1]));
            }
        });
        mapData.keyBy(line->line.f0)

//  todo 滑动窗口 每三秒计算一次前六秒的数据量
                .window(SlidingProcessingTimeWindows.of(Time.seconds(6),Time.seconds(3)))
                .reduce(new ReduceFunction<Tuple2<Integer, Integer>>() {
                    @Override
                    public Tuple2<Integer, Integer> reduce(Tuple2<Integer, Integer> value1, Tuple2<Integer, Integer> value2) throws Exception {
                        return Tuple2.of(value1.f0,value1.f1 + value2.f1);
                    }
                })

                .print();
        env.execute();
    }
}

给程序开一个单独的端口:nc -lk 9999

当程序运行后,在开的端口处发送数据并在控制台打印输出结果:

在 Apache Flink 中,聚合函数是用于将流数据进行聚合操作的函数,常用于实现基于时间窗口或者滑动窗口的聚合操作。 下面是一个使用 Flink 聚合函数的例子: ``` DataStream<Tuple2<String, Integer>> input = ...; // 按照 key 分组,计算每个 key 出现的次数 DataStream<Tuple2<String, Integer>> result = input .keyBy(0) .timeWindow(Time.seconds(10)) .aggregate(new CountAggregator()); // 自定义计数器聚合函数 public static class CountAggregator implements AggregateFunction<Tuple2<String, Integer>, Integer, Integer> { @Override public Integer createAccumulator() { return 0; } @Override public Integer add(Tuple2<String, Integer> value, Integer accumulator) { return accumulator + 1; } @Override public Integer getResult(Integer accumulator) { return accumulator; } @Override public Integer merge(Integer a, Integer b) { return a + b; } } ``` 上述例子中,我们首先定义了一个输入流 input,其中包含了一个 Tuple2 类型的元素,第一个元素为 String 类型的 key,第二个元素为 Integer 类型的 value。 接着我们使用了 keyBy() 方法按照 key 进行分组,并使用 timeWindow() 方法定义了一个大小为 10 秒的时间窗口。 最后我们使用了 aggregate() 方法来对每个窗口中的元素进行聚合操作,其中我们传入了一个自定义的计数器聚合函数 CountAggregator。 CountAggregator 实现了 AggregateFunction 接口,其中 createAccumulator() 方法用于创建一个初始的计数器,add() 方法用于将输入元素累加到计数器中,getResult() 方法用于返回计数器的结果,merge() 方法用于合并两个计数器的结果。 综上所述,上述例子中我们使用Flink 自带的 keyBy()、timeWindow() 和 aggregate() 方法,以及自定义的计数器聚合函数 CountAggregator,来实现了按照 key 进行分组并计算每个 key 出现次数的聚合操作。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yangjiwei0207

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值