flink MapState 更新存储对象问题

在使用flink中的状态管理器时,由于需求背景我选用了MapState存储结构,但是在使用过程中发现修改存储对象的时候并没有MapState中的值并没有自动更新,这让我产生了很大的疑惑,看官方文档和flink源码中我都一直把MapState认为是类似于Map结构的,那自然认为修改里面的存储对象时整个map会自动更新,但是实际使用和测试下来确发现不是这样。
先贴一段官方文档:

MapState<UK, UV>: This keeps a list of mappings. You can put key-value pairs into the state and retrieve an Iterable over all currently stored mappings. Mappings are added using put(UK, UV) or putAll(Map<UK, UV>). The value associated with a user key can be retrieved using get(UK). The iterable views for mappings, keys and values can be retrieved using entries(), keys() and values() respectively. You can also use isEmpty() to check whether this map contains any key-value mappings.

接下来再贴一下代码:
首先来看map中修改对象的case:

// 实体类
public class OutputEntity {
    private Integer amt;

    public static OutputEntity getOneOutput(Integer amt){
        OutputEntity output = new OutputEntity(amt);
        output.amt = 10;
        return output;
    }

    public OutputEntity(Integer amt){
        this.amt = amt;
    }

    public void incr(Integer newAmt){
        this.amt += newAmt;
    }

    public Integer getAmt() {
        return amt;
    }

    public void setAmt(Integer amt) {
        this.amt = amt;
    }

public class mapUpdate {
    public static void main(String[] args){
        Map<String, OutputEntity> newHashMap = new HashMap<String, OutputEntity>();
        newHashMap.put("key1", OutputEntity.getOneOutput(10));
        newHashMap.get("key1").incr(20);
        newHashMap.get("key1").incr(20);
        System.out.println(JSON.toJSONString(newHashMap));
    }
}

// 输出:{"key1":{"amt":50}}

可见一般map类型的可以直接修改存储对象,然后map会自动更新(这是由于java对象引用。。。。不展开叙述了)

但是对于MapState来说,下面举一个我的flink job中实际遇到的:

public class xxxFlatMapFunction extends RichFlatMapFunction<String, Output> {
    private static final Logger logger = LoggerFactory.getLogger(xxxFlatMapFunction.class);

    private transient MapState<String, OutputEntity> newMap;

    public void open(Configuration parameters) throws Exception {
        super.open(parameters);

        MapStateDescriptor<String, Boolean> mapStateDesc = new MapStateDescriptor<>(
                "xxState",
                TypeInformation.of(String.class),
                TypeInformation.of(new TypeHint<Output>() {}
        ));

        StateTtlConfig stateTtlConfig = StateTtlConfig.newBuilder(Time.days(3))
                .setStateVisibility(StateTtlConfig.StateVisibility.NeverReturnExpired)
                .setUpdateType(StateTtlConfig.UpdateType.OnCreateAndWrite)
                .cleanupInRocksdbCompactFilter(5000)
                .build();

        mapStateDesc.enableTimeToLive(stateTtlConfig);
        newMap = getRuntimeContext().getMapState(mapStateDesc);
    }


    @Override
    public void flatMap(String value, Collector<Output> out) throws Exception {
        try {
            newMap.put("key1", OutputEntity.getOneOutput(10));
            newMap.get("key1").incr(20);
            out.collect(newMap.get(dateKey));
           logger.info(JSON.toJSONString(newMap.get("key1")));
        } catch (Exception ex) {
            logger.info("xxProcessFunction exception:" + ex.toString(), ex);
            wrongCounter.add(1);
        }
    }
}

// 输出发现 newMap = {"key1":10}

对比发现使用MapState后,修改存储对象没有直接更新state里面的值,查了一些资料后发现更新与否和state背后的存储结构有关系:

如果应用程序使用InMemoryStateBackend或者FsStateBackend做为state的存储介质,则所有本地状态都存储在工作进程的JVM堆上,即状态后端只保存对象的引用。因此,修改对象时会直接修改状态。
如果state使用RocksDBStateBackend(比如本例中所使用的state存储),所有状态访问是先进行序列化和反序列化之后,然后读取/写入RocksDB。在这种情况下,修改对象不会对状态产生影响。

所以在使用map等数据结构存储对象时,当对象有修改后最好还是显示的对map进行更新,不论是java里的map等类型的数据结构还是像flink中的MapState这一类的结构。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Flink中的MapState是一种用于存储键值对数据的状态类型。它可以在算子的运行过程中维护和访问状态数据。MapState是一个类似于Java的Map的接口,它提供了put、get和remove等操作来操作键值对数据。 在Flink中,MapState可以被用于在算子的状态中存储和管理中间结果,以及在流处理任务中维护一些需要随时间变化的状态。它可以被广泛应用于各种场景,比如窗口操作、连接操作等。 要使用MapState,你需要先创建一个MapStateDescriptor对象来描述状态的名称和类型。然后,通过调用RuntimeContext的getState方法来获取一个MapState对象。接下来,你就可以使用MapState对象进行put、get、remove等操作了。 下面是一个简单的示例代码,展示了如何在Flink中使用MapState: ``` import org.apache.flink.api.common.functions.RichFlatMapFunction; import org.apache.flink.api.common.state.MapState; import org.apache.flink.api.common.state.MapStateDescriptor; import org.apache.flink.util.Collector; public class MyFlatMapFunction extends RichFlatMapFunction<String, String> { private MapState<String, Integer> mapState; @Override public void open(Configuration parameters) throws Exception { MapStateDescriptor<String, Integer> mapStateDescriptor = new MapStateDescriptor<>( "myMapState", String.class, Integer.class ); mapState = getRuntimeContext().getMapState(mapStateDescriptor); } @Override public void flatMap(String value, Collector<String> out) throws Exception { // 将value作为键,将长度作为值存储MapStatemapState.put(value, value.length()); // 从MapState中获取所有的键值对并输出 for (Map.Entry<String, Integer> entry : mapState.entries()) { out.collect(entry.getKey() + ": " + entry.getValue()); } } } ``` 在上面的示例中,我们在`open`方法中创建了一个`MapStateDescriptor`对象,并通过`getRuntimeContext().getMapState()`方法获取了一个`MapState`对象。在`flatMap`方法中,我们使用`mapState.put()`方法将`value`作为键,将其长度作为值存储到`MapState`中,并通过遍历`mapState.entries()`来获取所有的键值对并输出。 希望对你有帮助!如果有更多问题,请继续提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值