// If the left value is less than 0, return -1.
if (leftValue == null)
return -1;
return leftValue;
}
还可以通过Redis对事务的支持方法watch和multi来实现,类似于一个CAS方法的实现,如果对热数据有竞争,则会返回失败,然后重试直到成功:
/**
* Implemented by CAS. Minus a key by a value, then return the left value.
* If the left value is less than 0, return -1; if error, return -1.
*
* No synchronization, because redis client is not shared among multiple
* threads.
*
* @param key
* the key of the redis variable.
* @param value
* the value to minus off.
* @return the value left after minus. If it is less than 0, return -1; if
* error, return -1.
*/
public long decrByUntil0Cas(String key, long value) {
// If any error, return -1.
if (value <= 0)
return -1;
// Start the CAS operations.
jedis.watch(key);
// Start the transation.
Transaction tx = jedis.multi();
// Decide if the left value is less than 0, if no, terminate the
// transation, return -1;
String curr = tx.get(key).get();
if (Long.valueOf(curr) - value < 0) {
tx.discard();
return -1;
}
// Minus the key by the value
tx.decrBy(key, value);
// Execute the transaction and then handle the result
List
// If error, return -1;
if (result == null || result.isEmpty()) {
return -1;
}
// Extract the first result
for (Object rt : result) {
return Long.valueOf(rt.toString());
}
// The program never comes here.
return -1;
}
閱讀更多 DBAplus社群 的文章