Flink中的ProcessFunction API(侧输出流SideOutput)

大部分的 DataStream API 的算子的输出是单一输出,也就是某种数据类型的流。除了 split 算子,可以将一条流分成多条流,这些流的数据类型也都相同。process function 的 side outputs 功能可以产生多条流,并且这些流的数据类型可以不一样。一个 side output 可以定义为 OutputTag[X]对象,X 是输出流的数据类型。process function 可以通过 Context 对象发射一个事件到一个或者多个 side outputs。

案例:

package flink.chapter6ProcessFunction

import org.apache.flink.streaming.api.TimeCharacteristic
import org.apache.flink.streaming.api.functions.ProcessFunction
import org.apache.flink.streaming.api.functions.timestamps.BoundedOutOfOrdernessTimestampExtractor
import org.apache.flink.streaming.api.scala.{OutputTag, StreamExecutionEnvironment}
import org.apache.flink.streaming.api.windowing.time.Time
import org.apache.flink.util.Collector
import org.apache.flink.streaming.api.scala._

object Demo3 {
  def main(args: Array[String]): Unit = {
    val env = StreamExecutionEnvironment.getExecutionEnvironment
    env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime)
    env.setParallelism(1)
    val dataStream = env.socketTextStream("hadoop101",9999)

    val texStream = dataStream
      .map{
        line => val words = line.split("\t")
          (words(0).trim,words(1).trim.toLong,words(2).trim.toDouble)
      }
      .assignTimestampsAndWatermarks(
        new BoundedOutOfOrdernessTimestampExtractor[(String, Long, Double)](Time.seconds(2)) {
          override def extractTimestamp(t: (String, Long, Double)): Long = {
            t._2*1000
          }
        }
      ).process(new MySideOutputFun)
    texStream.print("texStream::::").setParallelism(1)
    texStream.getSideOutput(new OutputTag[String]("one")).print()
    texStream.getSideOutput(new OutputTag[String]("tow")).print()
    env.execute("Dmeo3")
  }
}
class MySideOutputFun extends ProcessFunction[(String, Long, Double),(String, Long, Double)]{
  // 定义一个侧输出标签
  lazy val one = new OutputTag[String]("one")
  lazy val tow = new OutputTag[String]("tow")

  override def processElement(i: (String, Long, Double),
                              context: ProcessFunction[(String, Long, Double), (String, Long, Double)]#Context,
                              collector: Collector[(String, Long, Double)]): Unit = {
    if(i._3<0){
      context.output(one," le one =  "+i._3)
    }else if(i._3>0 && i._3<32) {
      context.output(tow," le tow =  "+i._3)
    }else {
      collector.collect(i)
    }
  }
}

测试结果:如下图
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值