如何使用Aerospike Java客户端原子更新Map字段的指定key值
Aerospike 原子更新Map字段指定key实现方案
核心逻辑
利用Aerospike原生的CDT(复杂数据类型)操作API中的MapOperation,直接在服务端完成map字段指定key的更新,全程原子性,无并发竞态问题,不需要读取整个实体到客户端修改后再回写。
实现示例
1. 原生Aerospike Java客户端实现
import com.aerospike.client.AerospikeClient; import com.aerospike.client.Key; import com.aerospike.client.cdt.MapOperation; import com.aerospike.client.cdt.MapPolicy; import com.aerospike.client.cdt.MapOrder; import com.aerospike.client.cdt.MapWriteFlags; import com.aerospike.client.Value; // 你预先初始化好的AerospikeClient实例 AerospikeClient client = ...; // 构造 Aerospike 主键:参数依次为命名空间、Set名、主键值(对应实体类的cycle字段) Key recordKey = new Key(Constants.NAMESPACE, Constants.ABC_SET, "你业务对应的cycle值"); // 要更新的map内部的目标key String targetMapKey = "需要修改的map内key"; // 增量值:要增加传正数,要减少传负数,要直接设值可替换为put方法 double addValue = 2.5; // 执行原子更新操作 client.operate( null, // 写入策略,传null用默认策略即可 recordKey, MapOperation.increment( new MapPolicy(MapOrder.UNORDERED, MapWriteFlags.DEFAULT), "map", // 对应实体类中map字段对应的Bin名称,默认和字段名一致 Value.get(targetMapKey), Value.get(addValue) ) );
如果需要直接覆盖指定key的值而非增量修改,把MapOperation.increment替换为MapOperation.put即可。
2. Spring Data Aerospike 实现(适配你使用的@AerospikeEntity注解场景)
import org.springframework.data.aerospike.core.AerospikeTemplate; import org.springframework.beans.factory.annotation.Autowired; public class AbcService { @Autowired private AerospikeTemplate aerospikeTemplate; /** * 原子更新map字段指定key的值 * @param cycle 主键值(对应实体类的cycle字段) * @param targetMapKey map内部要更新的key * @param increment 增量值 */ public void updateMapValueAtomic(String cycle, String targetMapKey, double increment) { aerospikeTemplate.opsForMap() .increment(ABCModel.class, cycle, "map", targetMapKey, increment); } }
注意事项
- 当map中不存在目标key时,默认会自动创建该key并将值设为传入的增量值,不需要提前判断key是否存在
- 实体类中map的value类型为
AtomicDouble,Aerospike会自动做类型映射,读写都不需要额外转换 - 如果需要在更新的同时获取修改后的值,可以在operate方法中追加
MapOperation.get("map", Value.get(targetMapKey)),一次请求即可完成更新+查询,不需要额外调用查询接口
内容的提问来源于stack exchange,提问作者avinash kumar
相关产品推荐
相关产品推荐

