Consul 提供了一个简单的键值存储(KV store)。它可以用于保存动态配置、辅助服务间协作、建立领导选举以及其他开发者想要实现的功能。
有两种方法可以访问 Consul KV 存储:通过 HTTP API 或者 Consul KV CLI。下面通过 Consul KV CLI 的使用方法。
./consul kv get nginx/worker_connections
Error! No key exists at: nginx/worker_connections
查询没有此key,我们插入一个键值:
# 插入
./consul kv put nginx/worker_connections 65536
Success! Data written to: nginx/worker_connections
# 查询
./consul kv get nginx/worker_connections
65536
# 查看键值对元数据
./consul kv get -detailed nginx/worker_connections
CreateIndex 41706
Flags 0
Key nginx/worker_connections
LockIndex 0
ModifyIndex 41714
Session -
Value 65535
# 支持一个 64 位整数的标志位,它不用于 Consul 内部处理,但可以被客户端读取并赋予新的涵义。默认是0
./consul kv put -flags=12 nginx/worker_rlimit_nofile 65535
# 递归查询
./consul kv get -recurse
nginx/worker_connections:65535
nginx/worker_rlimit_nofile:65535
# 递归删除
./consul kv delete -recurse nginx
# 删除一个键值对
./consul kv delete nginx/worker_connections
Consul 可以原子性地进行检查并设置(Check-And-Set)操作,用 -cas 标识:
./consul kv put -cas -modify-index=123 foo bar
Success! Data written to: foo
./consul kv put -cas -modify-index=123 foo bar
Error! Did not write to foo: CAS failed
参考:
https://www.consul.io/api/kv.html
https://www.consul.io/docs/commands/kv.html