【云星数据---Apache Flink实战系列(精品版)】:Apache Flink高级特性与高级应用019-Flink中参数传递和容错设定003

183 篇文章 0 订阅
12 篇文章 0 订阅

3.通过ExecutionConfig向Function传递参数

执行程序

package code.book.batch.sinksource.scala

import org.apache.flink.api.common.functions.RichMapFunction
import org.apache.flink.api.scala.{DataSet, ExecutionEnvironment, _}
import org.apache.flink.configuration.Configuration

/**
  * Globally via the ExecutionConfig
  * *
  * Flink also allows to pass custom configuration values to the ExecutionConfig
  * interface of the environment. Since the execution config is accessible in all
  * (rich) user functions, the custom configuration will be available globally in all functions.
  */
object Parameters003scala {
  def main(args: Array[String]): Unit = {
    val env = ExecutionEnvironment.getExecutionEnvironment

    //1.准备工人数据
    case class Worker(name: String, salaryPerMonth: Double)
    val workers: DataSet[Worker] = env.fromElements(
      Worker("zhagnsan", 1356.67),
      Worker("lisi", 1476.67)
    )
    //2.准备工作月份数据,作为参数用Configuration传递出去
    val conf = new Configuration()
    conf.setString("month", "4")
    env.getConfig.setGlobalJobParameters(conf)

    //3.接受参数进行计算(如果要用Configuration传参,需要用RichFunction接受)
    workers.map(new RichMapFunction[Worker, Worker] {
      private var m = 0

      override def open(parameters: Configuration): Unit = {
        super.open(parameters)
        //3.1获取Configuration传递过来的参数
        val globalParams = this.getRuntimeContext.getExecutionConfig.getGlobalJobParameters
        m = globalParams.toMap.get("month").trim.toInt
      }

      override def map(w: Worker): Worker = {
        //3.2计算最新工人工资信息
        Worker(w.name, w.salaryPerMonth * m)
      }
    }).print
  }
}
执行效果
Worker(zhagnsan,5426.68)
Worker(lisi,5906.68)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值