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);
            }
        }
    }
}
相关推荐
武子康3 小时前
大数据-241 离线数仓 - 实战:电商核心交易数据模型与 MySQL 源表设计(订单/商品/品类/店铺/支付)
大数据·后端·mysql
IvanCodes3 小时前
一、消息队列理论基础与Kafka架构价值解析
大数据·后端·kafka
武子康1 天前
大数据-240 离线数仓 - 广告业务 Hive ADS 实战:DataX 将 HDFS 分区表导出到 MySQL
大数据·后端·apache hive
字节跳动数据平台2 天前
5000 字技术向拆解 | 火山引擎多模态数据湖如何释放模思智能的算法生产力
大数据
武子康2 天前
大数据-239 离线数仓 - 广告业务实战:Flume 导入日志到 HDFS,并完成 Hive ODS/DWD 分层加载
大数据·后端·apache hive
字节跳动数据平台3 天前
代码量减少 70%、GPU 利用率达 95%:火山引擎多模态数据湖如何释放模思智能的算法生产力
大数据
得物技术3 天前
深入剖析Spark UI界面:参数与界面详解|得物技术
大数据·后端·spark
大大大大晴天3 天前
Flink生产问题排障-HBase NotServingRegionException
flink·hbase
武子康3 天前
大数据-238 离线数仓 - 广告业务 Hive分析实战:ADS 点击率、购买率与 Top100 排名避坑
大数据·后端·apache hive
武子康4 天前
大数据-237 离线数仓 - Hive 广告业务实战:ODS→DWD 事件解析、广告明细与转化分析落地
大数据·后端·apache hive