【雲星資料---Apache Flink實戰系列(精品版)】:Apache Flink高階特性與高階應用019-Flink中引數傳遞和容錯設定003

雲星資料-大資料團隊發表於2017-11-20

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)

相關文章