Flink有界流实现(1)
flink实现有界流需要使用StreamExecutionEnvironment类,并且最后需要使用env.execute() 方法,有界和无界的算子有时候会有不同的
复杂的写法
package org.example.test;
import org.apache.flink.api.java.functions.KeySelector;
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.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;
/**
* DataSet API使用
*/
public class WordCountDataStream {
public static void main(String[] args) throws Exception {
//TODO 1、获取流的类
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
//TODO 2、读取文件
// DataStreamSource<String> stringDataStreamSource = env.readTextFile("input/test.txt");
DataStreamSource<String> stringDataStreamSource = env.socketTextStream("localhost", 9000, "\n");
//TODO 3 ETL
//TODO 3.1 转换成二元数组,简单ETL的过程
SingleOutputStreamOperator<Tuple2<String, Integer>> process = stringDataStreamSource.process(new ProcessFunction<String, Tuple2<String, Integer>>() {
@Override
public void processElement(String value, ProcessFunction<String, Tuple2<String, Integer>>.Context ctx, Collector<Tuple2<String, Integer>> out) throws Exception {
String[] words = value.split(" ");
for (String word : words) {
Tuple2<String, Integer> tuple2 = Tuple2.of(word, 1);
out.collect(tuple2);
}
}
});
//TODO 3.1 分组
KeyedStream<Tuple2<String, Integer>, String> tuple2StringKeyedStream = process.keyBy(new KeySelector<Tuple2<String, Integer>, String>() {
@Override
public String getKey(Tuple2<String, Integer> value) throws Exception {
return value.f0;
}
});
//TODO 3.2 聚合计算
SingleOutputStreamOperator<Tuple2<String, Integer>> sum = tuple2StringKeyedStream.sum(1);
//TODO 4、打印
sum.print();
//TODO 5、无界流需要这个不断执行的方法
env.execute();
}
}
lamb表达式写法
无界流在输出的时候前面会带上一个数字,这个数字是线程数