countWindow 数量窗口(滑动窗口【滑动窗口与滚动窗口的区别,在于滑动窗口会有数据元素重叠可能,而滚动窗口不存在元素重叠】)
示例环境
java.version: 1.8.x
flink.version: 1.11.1
示例数据源 (项目码云下载)
CountWindow.java
import com.flink.examples.DataSource;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.api.java.tuple.Tuple3;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import java.util.List;
/**
* @Description countWindow数量窗口(滑动窗口【滑动窗口与滚动窗口的区别,在于滑动窗口会有数据元素重叠可能,而滚动窗口不存在元素重叠】)
*/
public class CountWindow {
/*
窗口在处理流数据时,通常会对流进行分区;
数据流划分为:
keyed(根据key划分不同数据流区)
non-keyed(指没有按key划分的数据流区,指所有原始数据流)
*/
/**
* 遍历集合,按数量窗口滑动,返回窗口下每个性别分区下最大年龄
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
List<Tuple3<String, String, Integer>> tuple3List = DataSource.getTuple3ToList();
DataStream<Tuple2<String, Integer>> dataStream = env.fromCollection(tuple3List)
.map(new MapFunction<Tuple3<String, String, Integer>, Tuple2<String, Integer>>() {
@Override
public Tuple2<String, Integer> map(Tuple3<String, String, Integer> tuple3) throws Exception {
return new Tuple2<>(tuple3.f1,tuple3.f2);
}
})
.returns(Types.TUPLE(Types.INT,Types.INT))
.keyBy((KeySelector<Tuple2<String, Integer>, String>) k ->k.f0)
//按数量窗口滑动,每隔2个对分区前3个输入数据流,计算一次
.countWindow(3, 2)
//注意:计算变量为f1
.maxBy(1);
dataStream.print();
env.execute("flink CountWindow job");
}
}
打印结果
4> (2,32)
3> (1,30)