Flink Operator State 實例 實現ListCheckpointed

public interface ListCheckpointed<T extends Serializable> {
  // Checkpoint觸發時會調用這個方法,我們要實現具體的snapshot邏輯,比如將哪些本地狀態持久化
  List<T> snapshotState(long checkpointId, long timestamp) throws Exception;
  // 從上次Checkpoint中恢復數據到本地內存
  void restoreState(List<T> state) throws Exception;
}

ListCheckpointed接口類是CheckpointedFunction接口類的一種簡寫,ListCheckpointed提供的功能有限,只支持均勻分佈的ListState,不支持全量廣播的UnionListState。

CheckpointedFunction中的snapshotState方法一樣,這裏的snapshotState也是在做備份,但這裏的參數列表更加精簡,其中checkpointId是一個單調遞增的數字,用來表示某次Checkpoint,timestamp是Checkpoint發生的實際時間,這個方法以列表形式返回需要寫入存儲的狀態。restoreState方法用來初始化狀態,包括作業第一次啓動或者作業失敗重啓。參數是一個列表形式的狀態,是均勻分佈給這個算子子任務的狀態數據。

 

 可以自定義把哪些變量如何保存到檢查點,以及如何初始化、如何從檢查點恢復

 public class CountingFunction<T> implements MapFunction<T, Tuple2<T, Long>>, ListCheckpointed<Long> {
 
     // this count is the number of elements in the parallel subtask
     private long count;
 
     @Override
     public List<Long> snapshotState(long checkpointId, long timestamp) {
         // return a single element - our count
         return Collections.singletonList(count);
     }
 
     @Override
     public void restoreState(List<Long> state) throws Exception {
         // in case of scale in, this adds up counters from different original subtasks
         // in case of scale out, list this may be empty
         for (Long l : state) {
             count += l;
         }
     }
 
     @Override
     public Tuple2<T, Long> map(T value) {
         count++;
         return new Tuple2<>(value, count);
     }
 }

flink 1.9.2, java1.8

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