You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Aerospike单事务实现:无记录时设默认timeLeft值并获取

Solution

To atomically retrieve the timeLeft value for a given key (or create the record with timeLeft=6000 if it doesn't exist), you can use conditional operations with Aerospike's operate() method. Here's the modified code:

import com.aerospike.client.exp.Exp;

public Record someMethod(String num) {
    WritePolicy writePolicy = aerospikeRepo.getWritePolicy(null, ttl, true);
    
    // Only execute write operations if the record does NOT exist
    writePolicy.condition = Exp.not(Exp.recordExists());
    
    // Combine put (default value) and get operations in one atomic transaction
    Operation[] ops = new Operation[] {
        Operation.put(new Bin("timeLeft", 6000)),
        Operation.get("timeLeft")
    };
    
    return aerospikeRepo.operate(writePolicy, namespace, set, num, ops);
}

Breakdown

  • Conditional Put: The Exp.not(Exp.recordExists()) condition ensures the put operation only runs when no record exists for the specified key. This prevents overwriting any existing records.
  • Atomic Execution: All operations in operate() run as a single transaction. If the record is missing, the put creates it with the default timeLeft value, then the get retrieves that value. If the record exists, the put is skipped entirely, and the get returns the existing timeLeft value.
  • TTL Preservation: Your original getWritePolicy call retains the TTL configuration for any new records created.

Note

This approach requires Aerospike Server version 4.9 or later (when expression support was introduced) and a compatible Java client.


内容的提问来源于stack exchange,提问作者Suraj Chaudhary

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 00:10:20