DEV Community

loading...

Writing key values from Java to Consul

claudioaltamura profile image Claudio Altamura Originally published at claudioaltamura.de ・1 min read

How to write key values to Consul

In the first example we are going to use the HTTP API directly, in the second one we are going to use the Java Consul API ecwid. On Github you'll find all the examples. So, let's start.

HTTP API
In this example we store the value "buon giorno" with the key "message". And all you have to do is a REST PUT operation with v1/kv as a path. Here, Consul is reachable at http://127.0.0.1:8500. That's it.

var value = "buon giorno";
var keyValuePath = "/config/consul-example/greetings/message";
var resourceUrl = "http://127.0.0.1:8500/v1/kv" + keyValuePath;

HttpRequest request = HttpRequest.newBuilder()
  .uri(new URI(resourceUrl))
  .PUT(HttpRequest.BodyPublishers.ofString(value))
  .build();

HttpClient
  .newBuilder()
  .build()
  .send(request, HttpResponse.BodyHandlers.ofString());
Enter fullscreen mode Exit fullscreen mode

Java Consul API
The library is quite easy. First you have to create a ConsulClient with an URL. You use that ConsulClient for reading and writing. It's just set* (with a key and the value) and get* methods. With the getKVValue() you get a Response instance. And for the real value you have to call getDecodedValue(). :-)

ConsulClient consulClient = new ConsulClient("http://127.0.0.1:8500");

consulClient.setKVValue("/config/blueprint/greetings/note", "hello");

Response<GetValue> response = consulClient.getKVValue("/config/blueprint/greetings/note");

System.out.println("value: " + response.getValue().getDecodedValue());
Enter fullscreen mode Exit fullscreen mode

Links
https://www.consul.io/api-docs#http-methods
https://github.com/Ecwid/consul-api

Discussion (0)

pic
Editor guide