代码如下
package cn.kgc.transform
import org.apache.flink.streaming.api.functions.ProcessFunction
import org.apache.flink.streaming.api.scala._
import org.apache.flink.util.Collector
object SideOutputStream1 {
def main(args: Array[String]): Unit = {
//创建环境
val env = StreamExecutionEnvironment.getExecutionEnvironment
//设置并行度为1
env.setParallelism(1)
//接收数据
val input = env.fromElements(1, 2, 3, 4, 5, 6, 7, 8)
//定义标签名
val odd = new OutputTag[Int]("odd")
val even = new OutputTag[Int]("even")
//使用process算子来实现侧输出流
val result = input.process(new ProcessFunction[Int, Int] {
override def processElement(i: Int, context: ProcessFunction[Int, Int]#Context, collector: Collector[Int]): Unit = {
if (i % 2 == 0) {
context.output(even, i)
} else {
context.output(odd, i)
}
}
})
//结果输出
result.getSideOutput(even).print("偶数")
result.getSideOutput(odd).print("奇数")
//执行程序
env.execute()
}
}
结果展示
SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/D:/Software/apache-maven-3.5.4/repository/org/slf4j/slf4j-log4j12/1.6.1/slf4j-log4j12-1.6.1.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/D:/Software/apache-maven-3.5.4/repository/ch/qos/logback/logback-classic/1.1.2/logback-classic-1.1.2.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
SLF4J: Actual binding is of type [org.slf4j.impl.Log4jLoggerFactory]
奇数> 1
偶数> 2
奇数> 3
偶数> 4
奇数> 5
偶数> 6
奇数> 7
偶数> 8
Process finished with exit code 0