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