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 theputoperation 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, theputcreates it with the defaulttimeLeftvalue, then thegetretrieves that value. If the record exists, theputis skipped entirely, and thegetreturns the existingtimeLeftvalue. - TTL Preservation: Your original
getWritePolicycall 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
相关产品推荐
相关产品推荐

