consul配置watch handler
consul有两种方式注册watch handler
- 通过agent配置
- 通过consul watch命令行
如果想通过HTTP API注册handle,目前还不支持,不知道啥时候能支持。
- 通过agent配置注册
- 第一步,创建consul-watch.json
{
"watches": [
{
"type": "key",
"key": "foo/bar/baz",
"handler_type": "http",
"http_handler_config": {
"path":"http://10.0.2.15:8080/watch",
"method": "POST",
"header": {"x-foo":["bar", "baz"]},
"timeout": "10s",
"tls_skip_verify": false
}
}
]
}
把这个文件放置到consul的配置目录下面。
在这个例子中,我们监听KV值foo/bar/baz,然后把事件通知到endpoint:http://10.0.2.15:8080/watch
第二步,在地址http://10.0.2.15:8080/watch,启动handler处理程序。
第三步,触发更新操作(包括创建)
$ curl --request PUT --data "value1" http://localhost:8500/v1/kv/foo/bar/baz
在handler能收到HTTP请求,内容如下:
----- Request Start ----->
/watch
Host: 10.0.2.15:8080
User-Agent: Go-http-client/1.1
Content-Length: 112
Content-Type: application/json
X-Consul-Index: 16
X-Foo: bar
X-Foo: baz
Accept-Encoding: gzip
Connection: close
{"Key":"foo/bar/baz","CreateIndex":14,"ModifyIndex":16,"LockIndex":0,"Flags":0,"Value":"dmFsdWUx","Session":""}
<----- Request End -----
我们看到在数据域能够包含所有key信息,包括key和value域。
还有一种watch一个prefix的例子:
{
"watches": [
{
"type": "keyprefix",
"prefix": "foo2/",
"handler_type": "http",
"http_handler_config": {
"path":"http://10.0.2.15:8080/watch"
}
}
]
}
注册所有foo2/开头的key。
$ curl --request PUT --data "value1" http://localhost:8500/v1/kv/foo2/bar
收到HTTP消息:
----- Request Start ----->
/watch
Host: 10.0.2.15:8080
User-Agent: Go-http-client/1.1
Content-Length: 111
Content-Type: application/json
X-Consul-Index: 24
Accept-Encoding: gzip
Connection: close
[{"Key":"foo2/bar","CreateIndex":24,"ModifyIndex":24,"LockIndex":0,"Flags":0,"Value":"dmFsdWUx","Session":""}]
<----- Request End -----
- 通过consul watch命令注册
目前我看到的只能是handler是一个外部可执行程序的方式,还没有看到handler是一个endpoint的场景。
估计以后会支持吧。
其原理是注册一个可执行脚本,在watch事件触发的时候,把从consul收到的json内容以stdin的方式传递给脚本。然后用户可以在脚本里面处理自己的行为了。
第一步:创建处理脚本
$ cat consul-watch-handler.sh
#!/usr/bin/env sh
while read line
do
echo "line: "$line
done
第二步:通过watch命令注册handler
$ consul watch -type=keyprefix -prefix=foo3/ /consul-watch-handler.sh
这个地方有一点疑问,watch命令行并不会退出,感觉好诧异,为什么不退出呢(当然可以用&符号来后台运行的方式);个人觉得注册完了之后,注册事件本身已经完成了,命令应该退出,后面的处理消息属于监听事件行为,而不是注册事件行为,只要监听到事件发生,把通知回调到脚本就行了。
第三步:触发update
$ curl --request PUT --data "value1" http://localhost:8500/v1/kv/foo3/bar
第四步:查看consul-watch-handler.sh的输出
line: [{"Key":"foo3/bar","CreateIndex":113,"ModifyIndex":169,"LockIndex":0,"Flags":0,"Value":"dmFsdWUx","Session":""}]