【雲星資料---Apache Flink實戰系列(精品版)】:Apache Flink高階特性與高階應用016-Flink中廣播變數和分散式快取002

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

2.flink中的分散式快取

flink支援將檔案,分散式快取到worker節點,以便程式計算使用。

執行程式

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

import scala.collection.mutable.ListBuffer
import scala.io.Source

/**
  * hdfs:///input/flink/workcount.txt檔案內容如下:
  * zhagnsan:4
  * lisi:5
  */
object DistributedCache001 {
  def main(args: Array[String]): Unit = {
    val env = ExecutionEnvironment.getExecutionEnvironment
    //1.準備快取資料,
    val path = "hdfs:///input/flink/workcount.txt"
    env.registerCachedFile(path, "MyTestFile")

    //2.準備工人資料
    case class Worker(name: String, salaryPerMonth: Double)
    val workers: DataSet[Worker] = env.fromElements(
      Worker("zhagnsan", 1356.67),
      Worker("lisi", 1476.67)
    )

    //3.使用快取資料和工人資料做計算
    workers.map(new MyMapper()).print()
    class MyMapper() extends RichMapFunction[Worker, Worker] {
      private var lines: ListBuffer[String] = new ListBuffer[String]
      //3.1在open方法中獲取快取檔案
      override def open(parameters: Configuration): Unit = {
        super.open(parameters)
        //access cached file via RuntimeContext and DistributedCache
        val myFile = getRuntimeContext.getDistributedCache.getFile("MyTestFile")
        val lines = Source.fromFile(myFile.getAbsolutePath).getLines()
        lines.foreach(f = line => {
          this.lines.append(line)
        })
      }

      //3.2在map方法中使用獲取到的快取檔案內容
      override def map(worker: Worker): Worker = {
        var name = ""
        var month = 0
        //分解檔案中的內容
        for (s <- this.lines) {
          val tokens = s.split(":")
          if (tokens.length == 2) {
            name = tokens(0).trim
            if (name.equalsIgnoreCase(worker.name)) {
              month = tokens(1).trim.toInt
            }
          }
          //找到滿足條件的資訊
          if (name.nonEmpty && month > 0.0) {
            return Worker(worker.name, worker.salaryPerMonth * month)
          }
        }
        //沒有滿足條件的資訊
        Worker(worker.name, worker.salaryPerMonth * month)
      }
    }
  }
}

執行效果

Worker(zhagnsan,5426.68)
Worker(lisi,7383.35)

相關文章