Memcached CAS 命令

CAS(check-and-set)用版本号避免并发覆盖。

Beginner
Key Pointsgets 取出时带一个唯一版本号(cas token),写回时带上,版本变了就拒绝——乐观锁。

用法

Shell
gets counter
# 假设返回 VALUE counter 0 3 42 <cas=99>
cas counter 0 0 3 99
43
Output
VALUE counter 0 3 42
99
STORED

版本冲突

Shell
# 另一个客户端已改过,cas token 变了
cas counter 0 0 3 99
43
Output
EXISTS
CAS 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.

Friends & Partners