Flink的算子列表状态的使用

背景

算子的列表状态是平时比较常见的一种状态,本文通过官方的例子来看一下怎么使用算子列表状态

算子列表状态

算子列表状态支持应用的并行度扩缩容,如下所示:

使用方法参见官方示例,我加了几个注解:

java 复制代码
public class BufferingSink
        implements SinkFunction<Tuple2<String, Integer>>,
                   CheckpointedFunction {//要实现CheckpointedFunction接口

    private final int threshold;

   //算子操作状态对象--算子级别的
    private transient ListState<Tuple2<String, Integer>> checkpointedState;
    //本地变量,保存这个算子任务的本地变量--任务级别的 
    private List<Tuple2<String, Integer>> bufferedElements;

    public BufferingSink(int threshold) {
        this.threshold = threshold;
        this.bufferedElements = new ArrayList<>();
    }

//invoke方法中一般都是操作本地变量bufferedElements,不会直接操作算子列表状态
    @Override
    public void invoke(Tuple2<String, Integer> value, Context contex) throws Exception {
        bufferedElements.add(value);
        if (bufferedElements.size() >= threshold) {
            for (Tuple2<String, Integer> element: bufferedElements) {
                // send it to the sink
            }
            bufferedElements.clear();
        }
    }

    @Override
    public void snapshotState(FunctionSnapshotContext context) throws Exception {
        checkpointedState.clear();
        for (Tuple2<String, Integer> element : bufferedElements) {
            // 把本地变量的值设置到算子列表状态中,算子列表状态会自动会被持久化
            checkpointedState.add(element);
        }
    }

    @Override
    public void initializeState(FunctionInitializationContext context) throws Exception {
        ListStateDescriptor<Tuple2<String, Integer>> descriptor =
            new ListStateDescriptor<>(
                "buffered-elements",
                TypeInformation.of(new TypeHint<Tuple2<String, Integer>>() {}));
        // 定义算子列表状态
        checkpointedState = context.getOperatorStateStore().getListState(descriptor);

        if (context.isRestored()) {
        // 算子列表状态的值设置到本地变量中
            for (Tuple2<String, Integer> element : checkpointedState.get()) {
                bufferedElements.add(element);
            }
        }
    }
}
相关推荐
星辰_mya10 分钟前
Elasticsearch线上问题之OOM
大数据·elasticsearch·搜索引擎
忆~遂愿14 分钟前
Runtime 上下文管理:计算实例的生命周期、延迟最小化与上下文切换优化
java·大数据·开发语言·人工智能·docker
Elastic 中国社区官方博客15 分钟前
使用 Groq 与 Elasticsearch 进行智能查询
大数据·数据库·人工智能·elasticsearch·搜索引擎·ai·全文检索
BJ_Bonree17 分钟前
4月17日,博睿数据受邀出席GOPS全球运维大会2026 · 深圳站!
大数据·运维·人工智能
张彦峰ZYF27 分钟前
一套「策略化 Elasticsearch 召回平台」架构设计思路
大数据·elasticsearch·搜索引擎
Giggle121833 分钟前
外卖 O2O 系统怎么选?从架构到部署方式的完整拆解
大数据·架构
九.九1 小时前
CANN 算子生态的底层安全与驱动依赖:固件校验与算子安全边界的强化
大数据·数据库·安全
Coder个人博客7 小时前
Linux6.19-ARM64 mm mmu子模块深入分析
大数据·linux·车载系统·系统架构·系统安全·鸿蒙系统
财经三剑客11 小时前
AI元年,春节出行安全有了更好的答案
大数据·人工智能·安全
岁岁种桃花儿11 小时前
Flink CDC从入门到上天系列第一篇:Flink CDC简易应用
大数据·架构·flink