这篇文章主要介绍“Flink SideOutput怎么使用”,在日常操作中,相信很多人在Flink SideOutput怎么使用问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”Flink SideOutput怎么使用”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!
SideOutput方法:(侧输出)从主数据流中根据outputTag获取额外的输出流(分流场景下使用)
示例环境
java.version: 1.8.x flink.version: 1.11.1
示例数据源 (项目码云下载)
Flink 系例 之 搭建开发环境与数据
SideOutput.java
import com.flink.examples.DataSource; import org.apache.flink.api.java.tuple.Tuple3; import org.apache.flink.api.java.tuple.Tuple4; import org.apache.flink.streaming.api.datastream.DataStream; 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; import org.apache.flink.util.OutputTag; import java.util.List; /** * @Description SideOutput方法:(侧输出)从主数据流中根据outputTag获取额外的输出流(分流场景下使用) */ public class SideOutput { /** * 遍历集合,将数据流切分成多个流并打印 * @param args * @throws Exception */ public static void main(String[] args) throws Exception { final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); env.setParallelism(1); List<Tuple3<String, String, Integer>> tuple3List = DataSource.getTuple3ToList(); //Datastream DataStream<Tuple3<String, String, Integer>> dataStream = env.fromCollection(tuple3List); //自定义man和girl两个性别tag OutputTag<Tuple4<String, String, Integer, String>> manTag = new OutputTag<Tuple4<String, String, Integer, String>>("man"){}; OutputTag<Tuple4<String, String, Integer, String>> girlTag = new OutputTag<Tuple4<String, String, Integer, String>>("girl"){}; //将所有流数据输入到process做处理 SingleOutputStreamOperator<Tuple4<String, String, Integer, String>> output = dataStream.process(new ProcessFunction<Tuple3<String,String,Integer>, Tuple4<String, String, Integer, String>>() { @Override public void processElement(Tuple3<String, String, Integer> value, Context ctx, Collector<Tuple4<String, String, Integer, String>> out) throws Exception { //将数据流按不同的性别划分,创建新的Tuple4,分别绑定到不同性别的tag if (value.f1.equals("man")){ ctx.output(manTag, Tuple4.of(value.f0, value.f1, value.f2, "男")); }else { ctx.output(girlTag, Tuple4.of(value.f0, value.f1, value.f2, "女")); } } }); //获取指定tag的数据流 DataStream<Tuple4<String, String, Integer, String>> dataStream1 = output.getSideOutput(manTag); DataStream<Tuple4<String, String, Integer, String>> dataStream2 = output.getSideOutput(girlTag); //打印 dataStream1.print(); dataStream2.print(); env.execute("flink Split job"); } }
打印结果
(张三,man,20,男) (李四,girl,24,女) (王五,man,29,男) (刘六,girl,32,女) (伍七,girl,18,女) (吴八,man,30,男)
到此,关于“Flink SideOutput怎么使用”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。