2

I use REST API for accessing consul.

for example here is how I create an entry

curl -X PUT -d @- localhost:8500/v1/kv/example <<< FooValue

I want to add watches to consul that notify my service when a key-value is changed.

The documentation gives example of how http watches look like. But I am interested in how to attach this watches to consul using REST

I could not find examples of that

Thanks

Daniel Mann
  • 57,011
  • 13
  • 100
  • 120
brain storm
  • 30,124
  • 69
  • 225
  • 393

2 Answers2

0

As per the documentation in consul, currently watches can be added in two ways:

1.As a part of agent configuration

2.Using the watch command.

If you are interested in getting notified when the key value changes, you can do it with the help of 'refresh event' by using event listener. A task scheduler is inherently available to take care of this.

set the property as follows

spring.cloud.consul.config.watch.enabled=true

The watch uses a Spring TaskScheduler to schedule the call to consul.

In the relative path of kv store 'config/application/data' put your configuration,

for eg-> example: FooValue

You will get log info 'keys changed: [example: BarValue]' when you change the kv store data.

Harsha Vardhan Chakka
  • 1,357
  • 1
  • 9
  • 7
0

After reading source code of the watch command implementation, I found the way to do it in HTTP API. Note that this is undocumented, use it at your own risk.

Suppose to monitor the changes of KV under the path of /xxx. First emit the following request.

GET http://your-consul.com:8500/v1/kv/xxx?recurse=true&stale=true

Consul would response this request immediately.

Connection: keep-alive
Content-Length: 209
Content-Type: application/json
Date: Sun, 13 Nov 2022 00:27:04 GMT
Vary: Accept-Encoding
Via: 1.1 proxy-server (squid/5.5)
X-Cache: MISS from proxy-server
X-Cache-Lookup: MISS from proxy-server:3128
X-Consul-Default-Acl-Policy: allow
X-Consul-Index: 3386097
X-Consul-Knownleader: true
X-Consul-Lastcontact: 0
X-Consul-Query-Backend: blocking-query

The X-Consul-Index http header is what we are looking for.

Then emits another request with the index.

GET http://your-consul.com:8500/v1/kv/xxx?index=3386097&recurse=true&stale=true

Now this request will stuck till a change occurs. When this request is responsed, the payload contains the details of all children KV at given path. X-Consul-Index will also be included in response HTTP header, you need update the index query string if you want to watch again.

So generally, you can watch changes via HTTP API as what the consul tool does. Note that you need implement the logic carefully, to handle timeout / network error / etc.

Mr.Wang from Next Door
  • 13,670
  • 12
  • 64
  • 97