DEV Community

Claudio Altamura
Claudio Altamura

Posted on • Originally published at claudioaltamura.de

2

Writing key values from Java to Consul

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

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more →

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more