配置
创建watcher.json
文件,放在consul
配置目录下,启动consul时指定-config-dir
:
{
"watches": [
{
"type": "key",
"key": "foo/data",
"handler_type": "http",
"http_handler_config": {
"path":"http://127.0.0.1:8763/watch",
"method": "POST",
"header": {"x-foo":["bar", "baz"]},
"timeout": "10s",
"tls_skip_verify": false
}
}
]
}
创建handle
创建一个http服务
用于接收变更的key
,http://127.0.0.1:8763/watch
@RequestMapping("/watch")
public void watcher(HttpServletRequest request) throws IOException {
System.out.println(request.getMethod());
BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
String str = "";
String wholeStr = "";
while ((str = reader.readLine()) != null) {
wholeStr += str;
}
System.out.println("body:" + wholeStr);
}
测试
在consul ui
中新增 或者修改foo/data
这个key值,watcher
就会收到这个更新后的值
POST
body:{"Key":"foo/data","CreateIndex":12,"ModifyIndex":12,"LockIndex":0,"Flags":0,"Value":"YWFhYWFhYQ==","Session":""}
POST
body:{"Key":"foo/data","CreateIndex":12,"ModifyIndex":17,"LockIndex":0,"Flags":0,"Value":"YWFhYWFhYXNzc3NkZHNkZHNk","Session":""}
POST
body:{"Key":"foo/data","CreateIndex":12,"ModifyIndex":25,"LockIndex":0,"Flags":0,"Value":"ewogICJ0ZXN0IjoidGVzdCIsCiAgInRlc3QyIjoidDMzM2VzdCIKfQ==","Session":""}
value为base64编码
,解码后得到需要的值。
sh脚本
handle
除了是http
,还可以是sh脚本
,如
{
"type": "key",
"key": "foo/bar/baz",
"handler_type": "script",
"args": ["/usr/bin/my-service-handler.sh", "-redis"]
}
官网说明
以下摘自官网:https://www.consul.io/docs/agent/watches.html#key
Watch Types/支持的类型
The following types are supported. Detailed documentation on each is below:
- key - Watch a specific KV pair
- keyprefix - Watch a prefix in the KV store
- services - Watch the list of available services
- nodes - Watch the list of nodes
- service- Watch the instances of a service
- checks - Watch the value of health checks
- event - Watch for custom user events
{
"type": "key",
"key": "foo/bar/baz",
"args": ["/usr/bin/my-service-handler.sh", "-redis"]
}
{
"type": "keyprefix",
"prefix": "foo/",
"args": ["/usr/bin/my-service-handler.sh", "-redis"]
}
{
"type": "service",
"service": "redis",
"args": ["/usr/bin/my-service-handler.sh", "-redis"],
"tag": "bar"
}