Operator、Keyed State及Redistribute

1.Operator State使用

目前Operator State托管状态只是支持List类型的
(在使用Operator State时,要注意并行度的问题,很有可能因为并行度设置大于1,影响预期效果)
1.1 实现CheckpointedFunction接口
必须实现的两个方法:

@Override
public void initializeState(FunctionInitializationContext functionInitializationContext) throws Exception {

}
public void snapshotState(FunctionSnapshotContext functionSnapshotContext) throws Exception {

}

snapshotState是在checkpoint执行时调用;
initializeState在第一次初始化时调用或者在较早的checkpoint恢复时调用

1.2 实现ListCheckpointed接口
(与CheckpointedFunction不同,只会用ListState的重分配方式)
同样也是实现两个方法,分别是snapshotState和restoreState

2.Operator State的Redistribute

Redistribute:当Operator改变并发度的时候(Rescale),会触发状态的Redistribute,即Operator State里面的数据会重新分配到Operator的Task实例。
e.g 某Operator的并行度由3改为2
<1> ListState:
就是在initializeState方法中
context.getOperatorStateStore().getListState()

 
image.png

<2> UnionListState
就是在initializeState方法中
context.getOperatorStateStore().getUnionListState()


 
image.png

<3> BroadcastState
context.getOperatorStateStore().getBroadcastState()


 
image.png

总结:


 
image.png

3.Keyed State Redistribute

Key被Redistribute到哪一个Task,对应的Keyed State就会被Redistribute到哪一个Task。
Keyed State Redistribute是基于Key Group来做分配的:
<1> 将key分为group
<2> 每个key分配到唯一的group
<3> 将group分配给task实例
<4> Key group由最大并行度的大小决定
<5> Keyed State最终分配到哪一个Task:
— hash=hash(key)
— key group=hash%numOfKeyGroups
— subtask=key group*parallelism/numOfKeyGroups

4.Keyed State TTL

任何类型的keyed state都可以设置TTL,如果TTL已经配置,且状态值已过期,则会以最佳方式清理。
所有State collection都支持条目级别的TTL,即list、map中的条目独立expire。

StateTtlConfig ttlConfig=StateTtlConfig
                    .newBuilder(Time.seconds(1))
                    .setUpdateType(StateTtlConfig.UpdateType.OnCreateAndWrite)
                    .setStateVisibility(StateTtlConfig.StateVisibility.NeverReturnExpired)
                    .build();

 ValueStateDescriptor<String> stateDescriptor=new ValueStateDescriptor<String>("text state",String.class);
 stateDescriptor.enableTimeToLive(ttlConfig);

1.Refresh策略(默认是OnCreateAndWrite):设置如何更新KeyedState的 最后访问时间
<1> StateTtlConfig.UpdateType.Distabled — 禁用TTL永不过期
<2> StateTtlConfig.UpdateType.OnCreateAndWrite — 每次写操作均更新State的最后访问时间(Create、Update)
<3>StateTtlConfig.UpdateType.OnReadAndWrite— 每次读写操作均会更新State的最后访问时间

2.状态可见性(默认是NeverReturnExpired):这是用来设置是否返回已经过期的值(比如说该值过期了,但是还未清理,正好被访问)
StateTtlConfig.StateVisibility.NeverReturnExpired— 永不返回过期状态
StateTtlConfig.StateVisibility.ReturnExpiredIfNotCleanedUp — 可以返回过期但是尚未被清理的状态值

3.Ttl time scale
目前支持ProcessingTime

4.过期状态清理
默认:已经过期的数据被显示读取时才会清理(可能会导致状态越来越大,后续版本会改进)
FULL_STATE_SCAN_SNAPSHOT:在checkpoint时候清理full snapshot中的expired state

链接:https://www.jianshu.com/p/f15c7d8c6d77
posted @ 2019-08-17 16:43  舞羊  阅读(405)  评论(0编辑  收藏  举报