Spark Streaming之updateStateByKey以及基於緩存的實時wordcount程序

updateStateByKey

updateStateByKey操作,可以讓我們爲每個key維護一份state,並持續不斷的更新該state。

  1. 首先,要定義一個state,可以是任意的數據類型;
  2. 其次,要定義state更新函數——指定一個函數如何使用之前的state和新值來更新state。
    對於每個batch,Spark都會爲每個之前已經存在的key去應用一次state更新函數,無論這個key在batch中是否有新的數據。如果state更新函數返回none,那麼key對應的state就會被刪除。
    當然,對於每個新出現的key,也會執行state更新函數。
    注意,updateStateByKey操作,要求必須開啓Checkpoint機制。

案例:基於緩存的實時wordcount程序(在實際業務場景中,這個是非常有用的)
Java版本

public class UpdateStateByKeyWordCount {
    public static void main(String[] args) {
        SparkConf conf = new SparkConf().setAppName("UpdateStateByKeyWordCountJava").setMaster("local[2]");
        JavaStreamingContext streamingContext = new JavaStreamingContext(conf, Durations.seconds(10));

        // 第一點,如果要使用updateStateByKey算子,就必須設置一個checkpoint目錄,開啓checkpoint機制
        // 這樣的話才能把每個key對應的state除了在內存中有,那麼是不是也要checkpoint一份
        // 因爲你要長期保存一份key的state的話,那麼spark streaming是要求必須用checkpoint的,以便於在
        // 內存數據丟失的時候,可以從checkpoint中恢復數據

        // 開啓checkpoint機制,很簡單,只要調用jssc的checkpoint()方法,設置一個hdfs目錄即可
        streamingContext.checkpoint("hdfs://hadoop-100:9000/streamingCheckpoint");

        // 然後先實現基礎的wordcount邏輯
        JavaReceiverInputDStream<String> lines = streamingContext.socketTextStream("hadoop-100", 9999);

        JavaDStream<String> words = lines.flatMap(new FlatMapFunction<String, String>() {
            @Override
            public Iterable<String> call(String s) throws Exception {
                return Arrays.asList(s.split(" "));
            }
        });

        JavaPairDStream<String, Integer> wordNumber = words.mapToPair(new PairFunction<String, String, Integer>() {
            @Override
            public Tuple2<String, Integer> call(String s) throws Exception {
                return new Tuple2<>(s, 1);
            }
        });

        // 到了這裏,就不一樣了,之前的話,是不是直接就是pairs.reduceByKey
        // 然後,就可以得到每個時間段的batch對應的RDD,計算出來的單詞計數
        // 然後,可以打印出那個時間段的單詞計數
        // 但是,有個問題,你如果要統計每個單詞的全局的計數呢?
        // 就是說,統計出來,從程序啓動開始,到現在爲止,一個單詞出現的次數,那麼就之前的方式就不好實現
        // 就必須基於redis這種緩存,或者是mysql這種db,來實現累加

        // 但是,我們的updateStateByKey,就可以實現直接通過Spark維護一份每個單詞的全局的統計次數
        JavaPairDStream<String, Integer> result = wordNumber.updateStateByKey(
                // 這裏的Optional,相當於Scala中的樣例類,就是Option,可以這麼理解
                // 它代表了一個值的存在狀態,可能存在,也可能不存在
                new Function2<List<Integer>, Optional<Integer>, Optional<Integer>>() {

            // 這裏兩個參數
            // 實際上,對於每個單詞,每次batch計算的時候,都會調用這個函數
            // 第一個參數,values,相當於是這個batch中,這個key的新的值,可能有多個吧
            // 比如說一個hello,可能有2個1,(hello, 1) (hello, 1),那麼傳入的是(1,1)
            // 第二個參數,就是指的是這個key之前的狀態,state,其中泛型的類型是你自己指定的
            @Override
            public Optional<Integer> call(List<Integer> v1, Optional<Integer> v2) throws Exception {
                // 首先定義一個全局的單詞計數
                Integer nowValue = 0;

                // 其次,判斷,state是否存在,如果不存在,說明是一個key第一次出現
                // 如果存在,說明這個key之前已經統計過全局的次數了
                if(v2.isPresent()) {
                    nowValue = v2.get();
                }

                // 接着,將本次新出現的值,都累加到newValue上去,就是一個key目前的全局的統計次數
                for(Integer v : v1) {
                    nowValue += v;
                }
                return Optional.of(nowValue);
            }
        });

        // 到這裏爲止,相當於是,每個batch過來是,計算到pairs DStream,就會執行全局的updateStateByKey
        // 算子,updateStateByKey返回的JavaPairDStream,其實就代表了每個key的全局的計數,打印出來
        result.print();
        streamingContext.start();
        streamingContext.awaitTermination();
        streamingContext.close();
    }
}

Scala版本

object UpdateStateByKeyWordCount {
  def main(args: Array[String]): Unit = {
    val conf = new SparkConf().setAppName("UpdateStateByKeyWordCountScala").setMaster("local[2]")
    val streamingContext = new StreamingContext(conf, Seconds(10))

    streamingContext.checkpoint("hdfs://hadoop-100:9000/streamingCheckpoint")

    val lines = streamingContext.socketTextStream("hadoop-100", 9999)

    val words = lines.flatMap(line => line.split(" "))

    val wordNumber = words.map(word => (word, 1))

    val result = wordNumber.updateStateByKey((values:Seq[Int], state:Option[Int]) => {
      var newValue = state.getOrElse(0)
      for(v <- values) newValue += v
      Option(newValue)
    })

    result.print()

    streamingContext.start()
    streamingContext.awaitTermination()
  }
}


 

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