UpdateStateByKey操作

官網原話:

updateStateByKey操作允許您在使用新信息不斷更新時保持任意狀態。要使用它,您必須執行兩個步驟。

  1. 定義狀態 - 狀態可以是任意數據類型。
  2. 定義狀態更新功能 - 使用函數指定如何使用先前狀態和輸入流中的新值更新狀態。

在每個批處理中,Spark都會對所有現有key應用狀態更新功能,無論它們是否在批處理中都有新數據。如果更新函數返回,None則將刪除key-valu

 

/**
   * Return a new "state" DStream where the state for each key is updated by applying
   * the given function on the previous state of the key and the new values of each key.
   * Hash partitioning is used to generate the RDDs with Spark's default number of partitions.
   * @param updateFunc State update function. If `this` function returns None, then
   *                   corresponding state key-value pair will be eliminated.
   * @tparam S State type
   */
  def updateStateByKey[S: ClassTag](
      updateFunc: (Seq[V], Option[S]) => Option[S]
    ): DStream[(K, S)] = ssc.withScope {
    updateStateByKey(updateFunc, defaultPartitioner())
  }

計算需要Partitioner。因爲Hash高效率且不做排序,所以默認Partitioner是HashPartitoner。

源碼中發現有七種重載函數,自行翻閱。github源碼

package com.ruozedata.G5
import org.apache.spark.streaming.{Seconds, StreamingContext}
import org.apache.spark.{HashPartitioner, SparkConf, SparkContext}
import org.apache.log4j.Level
import org.apache.log4j.Logger
object updateStateByKey_test {
  Logger.getLogger("org.apache.spark").setLevel(Level.ERROR)

  val updateFunc = (iter: Iterator[(String, Seq[Int], Option[Int])]) => {
    //iter.flatMap(k=>Some(k._2.sum + k._3.getOrElse(0)).map(x=>(k._1,x)))
    //iter.map{case(x,y,z)=>Some(y.sum + z.getOrElse(0)).map(m=>(x, m))}
    //iter.map(k => (k._1, k._2.sum + k._3.getOrElse(0)))
    iter.map{ case(word, current_count, history_count) => (word, current_count.sum + history_count.getOrElse(0)) }
  }

  def main(args: Array[String]) {
   // LoggerLevels.setStreamingLogLevels()
    //StreamingContext
    val conf = new SparkConf().setAppName("test_update").setMaster("local[2]")
    val sc = new SparkContext(conf)
    //updateStateByKey必須設置setCheckpointDir
    sc.setCheckpointDir("Z://check")
    val ssc = new StreamingContext(sc, Seconds(5))
    val ds = ssc.socketTextStream("hadoop001", 9998)
    val result = ds.flatMap(_.split(" ")).map((_, 1)).updateStateByKey(
      updateFunc, new HashPartitioner(sc.defaultParallelism), true)
    result.print()
    ssc.start()
    ssc.awaitTermination()
  }
}

例子如上所示。配合nc -lk 9999使用。

由於統計全局,所以需要checkpoint數據會佔用較大的存儲。而且效率也不高。數據很多的時候不建議使用updateStateByKey

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章