etcd 基础10

2022-01-20 10:42:35 浏览数 (2)

条件操作

CompareAndSwap (CAS) 其实就是条件操作,或是判断执行

先进行比较,然后根据比较结果来决定是否进行后面的操作,可以用于构建分布式锁机制(协调服务)

Note: CompareAndSwap 不能用于目录,如果测试用于目录,会获得 102 “Not a file” 的错误

Item

Comment

prevValue

比较当前的值

prevIndex

比较当前的modifiedIndex

prevExist

检查key是否存在,如果是 true 就是一个更新操作; 如果是 false 就是一个创建操作

代码语言:javascript复制
[root@docker ~]# curl http://127.0.0.1:2379/v2/keys/foo -XPUT -d value=one
{"action":"set","node":{"key":"/foo","value":"one","modifiedIndex":89,"createdIndex":89},"prevNode":{"key":"/foo","value":"abc","moddex":54}}
[root@docker ~]# curl http://127.0.0.1:2379/v2/keys/foo?prevExist=false -XPUT -d value=three
{"errorCode":105,"message":"Key already exists","cause":"/foo","index":89}
[root@docker ~]# curl http://127.0.0.1:2379/v2/keys/foo?prevValue=two -XPUT -d value=three
{"errorCode":101,"message":"Compare failed","cause":"[two != one]","index":89}
[root@docker ~]# curl http://127.0.0.1:2379/v2/keys/foo?prevValue=one -XPUT -d value=five
{"action":"compareAndSwap","node":{"key":"/foo","value":"five","modifiedIndex":90,"createdIndex":89},"prevNode":{"key":"/foo","value9,"createdIndex":89}}
[root@docker ~]# curl http://127.0.0.1:2379/v2/keys/foo?prevIndex=99 -XPUT -d value=xxx
{"errorCode":101,"message":"Compare failed","cause":"[99 != 90]","index":90}
[root@docker ~]# curl http://127.0.0.1:2379/v2/keys/foo?prevIndex=90 -XPUT -d value=xxx
{"action":"compareAndSwap","node":{"key":"/foo","value":"xxx","modifiedIndex":91,"createdIndex":89},"prevNode":{"key":"/foo","value"0,"createdIndex":89}}
[root@docker ~]# 

0 人点赞