大数据——Flink 侧输出流练习(将集合中的整数按奇偶写入不同的流中)

该博客展示了如何在Apache Flink中通过`ProcessFunction`处理数据流,并利用侧输出(side output)功能将数据分为偶数和奇数两部分。代码创建了一个流处理环境,设置并行度,接收数据,定义了两个输出标签`odd`和`even`,然后使用`processElement`方法根据数字的奇偶性将其发送到相应的侧输出流。最终,程序打印出奇数和偶数流的结果。
摘要由CSDN通过智能技术生成

代码如下

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

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Vicky_Tang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值