上篇:union的使用
connect的使用
- 可以将两个流不一致的类型连接一起
- 可以共享状态
直接上代码
package cn._51doit.flink.day03;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.ConnectedStreams;
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.co.CoMapFunction;
/**
* connect的使用
* 程序操作:
* nc -l 8888的窗口输入字符串,将会转成大写输出;
* nc -l 8888的窗口输入数字,将会运算输出
*/
public class ConnectDemo {
public static void main(String[] args) throws Exception {
StreamExecutionEnvironment env = StreamExecutionEnvironment.createLocalEnvironmentWithWebUI(new Configuration());
DataStreamSource<String> lines1 = env.socketTextStream("Master", 8888);
SingleOutputStreamOperator<Integer> lines2 = env.socketTextStream("Master", 9999).map(s -> Integer.parseInt(s));
//将两个流connect【连接】
ConnectedStreams<String, Integer> connected = lines1.connect(lines2);
SingleOutputStreamOperator<String> result = connected.map(new CoMapFunction<String, Integer, String>() {
//对第一个流进行map运算的方法
@Override
public String map1(String value) throws Exception {
return value.toUpperCase();
}
//对第二个流进行map运算的方法
@Override
public String map2(Integer value) throws Exception {
return (value * 10) + "";
}
//这两个流的map方法执行完的返回值会放到新的流中
});
result.print();
env.execute();
}
}