Apply算子:对窗口内的数据流进行处理
示例环境
java.version: 1.8.x
flink.version: 1.11.1
示例数据源 (项目码云下载)
Apply.java
import com.flink.examples.DataSource;
import org.apache.flink.api.java.functions.KeySelector;
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 org.apache.flink.streaming.api.functions.windowing.WindowFunction;
import org.apache.flink.streaming.api.windowing.windows.GlobalWindow;
import org.apache.flink.util.Collector;
import java.util.Iterator;
import java.util.List;
/**
* @Description Apply方法:对窗口内的数据流进行处理
*/
public class Apply {
/**
* 遍历集合,分别打印不同性别的总人数与年龄之和
* @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<String> dataStream = env.fromCollection(tuple3List)
.keyBy((KeySelector<Tuple3<String, String, Integer>, String>) k -> k.f1)
//按数量窗口滚动,每3个输入窗口数据流,计算一次
.countWindow(3)
//只能基于Windowed窗口Stream进行调用
.apply(
//WindowFunction<IN, OUT, KEY, W extends Window>
new WindowFunction<Tuple3<String, String, Integer>, String, String, GlobalWindow>() {
/**
* 处理窗口数据集合
* @param s 从keyBy里返回的key值
* @param window 窗口类型
* @param input 从窗口获取的所有分区数据流
* @param out 输出数据流对象
* @throws Exception
*/
@Override
public void apply(String s, GlobalWindow window, Iterable<Tuple3<String, String, Integer>> input, Collector<String> out) throws Exception {
Iterator<Tuple3<String, String, Integer>> iterator = input.iterator();
int total = 0;
int i = 0;
while (iterator.hasNext()){
Tuple3<String, String, Integer> tuple3 = iterator.next();
total += tuple3.f2;
i ++ ;
}
out.collect(s + "共:"+i+"人,累加总年龄:" + total);
}
});
dataStream.print();
env.execute("flink Filter job");
}
}
打印结果
4> girl共:3人,累加总年龄:74
2> man共:3人,累加总年龄:79