Memcached CAS 命令
CAS(check-and-set)用版本号避免并发覆盖。
Key Pointsgets 取出时带一个唯一版本号(cas token),写回时带上,版本变了就拒绝——乐观锁。
用法
Shell
gets counter
# 假设返回 VALUE counter 0 3 42 <cas=99>
cas counter 0 0 3 99
43Output
VALUE counter 0 3 42
99
STORED版本冲突
Shell
# 另一个客户端已改过,cas token 变了
cas counter 0 0 3 99
43Output
EXISTSCAS is memcached's only concurrency-safe write: gets the token, cas with it; if changed meanwhile it returns EXISTS, just re-read and retry. Use it for counters/stock instead of append.
用法
Shell
gets counter
# 假设返回 VALUE counter 0 3 42 <cas=99>
cas counter 0 0 3 99
43Output
VALUE counter 0 3 42
99
STORED版本冲突
Shell
# 另一个客户端已改过,cas token 变了
cas counter 0 0 3 99
43Output
EXISTSCAS 是 memcached 唯一的并发安全写机制:先
gets 拿 token,再 cas 带 token 写回;期间别人改过则回 EXISTS,自己重读重试即可。用它做计数器/库存扣减比 append 安全。