读写 KV Store
demo: https://github.com/felicityin/consul-test
What is consul’s KV store ?
Consul’s KV store is one of the feature available in Consul and has the ability to store distributed Key-value.
It is mainly used for dynamic configuration, feature flagging, coordination, leader election, and also has many other uses apart from these.
Does Consul persist the Key Value store?
I ended up running the progrium/docker-consul image on Docker and adding some key-value pairs. After shutting it down with Ctrl-C, the values were still there when I restarted the container. I also killed Consul from the command line via
docker exec
, and the data was also persisted.The progrium/docker-consul image persisted all the data in the /data directory.
$ export CONSUL_HTTP_TOKEN=bae91595-fe01-9fe5-ab0a-c84f23eebd5e $ export CONSUL_HTTP_ADDR=127.0.0.1:8500 $ consul kv put test-key 1 Success! Data written to: test-key
curl --location --request PUT 'http://127.0.0.1:8500/v1/kv/test-key' \ --header 'x-consul-token: bae91595-fe01-9fe5-ab0a-c84f23eebd5e' \ --header 'Content-Type: application/json' \ --data 1
$ export CONSUL_HTTP_TOKEN=bae91595-fe01-9fe5-ab0a-c84f23eebd5e $ export CONSUL_HTTP_ADDR=127.0.0.1:8500 $ consul kv get test-key 1
curl \ --header "X-Consul-Token: bae91595-fe01-9fe5-ab0a-c84f23eebd5e" \ http://127.0.0.1:8500/v1/kv/test-key
watch kv 底层调用的是 get kv
$ export CONSUL_HTTP_TOKEN=bae91595-fe01-9fe5-ab0a-c84f23eebd5e $ export CONSUL_HTTP_ADDR=127.0.0.1:8500 $ consul watch -type=key -key=test-key { "Key": "test-key", "CreateIndex": 11993754, "ModifyIndex": 11993754, "LockIndex": 0, "Flags": 0, "Value": "MQ==", # base64 编码 "Session": "" }
读写 KV Token 权限
测试 279bd243-284b-f2d8-2bf0-f4782b8af34d 只拥有读取 key 前缀为 group/ 的 kv 的权限:
curl \
--header "X-Consul-Token: 279bd243-284b-f2d8-2bf0-f4782b8af34d" \
http://127.0.0.1:8500/v1/kv/group/test-key
[{"LockIndex":0,"Key":"group/test-key","Flags":0,"Value":"MQ==","CreateIndex":11998693,"ModifyIndex":11998693}]
curl \
--header "X-Consul-Token: 279bd243-284b-f2d8-2bf0-f4782b8af34d" \
http://127.0.0.1:8500/v1/kv/groups/test-key
Permission denied
51e1ddf4-6dff-8d22-5f6e-6c35921eb38a 只拥有读写 key 前缀为 group/ 的 kv 的权限:
curl --location --request PUT 'http://127.0.0.1:8500/v1/kv/group/test-key' \
--header 'x-consul-token: 51e1ddf4-6dff-8d22-5f6e-6c35921eb38a' \
--header 'Content-Type: application/json' \
--data 7
true
curl --location --request PUT 'http://127.0.0.1:8500/v1/kv/groups/test-key' \
--header 'x-consul-token: 51e1ddf4-6dff-8d22-5f6e-6c35921eb38a' \
--header 'Content-Type: application/json' \
--data 7
Permission denied
curl \
--header "X-Consul-Token: 51e1ddf4-6dff-8d22-5f6e-6c35921eb38a" \
http://127.0.0.1:8500/v1/kv/group/test-key
[{"LockIndex":0,"Key":"group/test-key","Flags":0,"Value":"MQ==","CreateIndex":11998693,"ModifyIndex":11998693}]
curl \
--header "X-Consul-Token: 51e1ddf4-6dff-8d22-5f6e-6c35921eb38a" \
http://127.0.0.1:8500/v1/kv/groups/test-key
Permission denied
没有评论