Skip to content

Code Examples

Jon Huang edited this page Nov 30, 2024 · 7 revisions

Code Examples for using the library

Creating the ConsulClient

The ConsulClient is the crux of the entire library, you will be using this class to make API calls directly to Consul. At the most basic form, you can invoke the default ConsulClient constructor which will connect to Consul at http://localhost:8500.

ConsulClient client = new ConsulClient("localhost");

Additional parameters can be configured to specify the Consul host, port, path, HTTP/S transport, and Consul API token. As an example of configuring the additional options:

ConsulRawClient.Builder b = new ConsulRawClient.Builder()
    .setHost('172.16.0.1')
    .setPort(8501)
    .setPath('myConsulPath') // This will give a full URI path of https://172.16.0.1:8501/myConsulPath
    .setProxy(...) // Set proxy settings
    .setTlsConfig(...) // Deprecated, provided for legacy implementations. Please migrate to "setSSLContext" as soon as possible
    .setSSLContext(...) // Set your own `javax.net.ssl.SSLContext` for building the Java HttpClient instance
    .setSSLParameters(...) // Set your own `javax.net.ssl.SSLParameters` for building the Java HttpClient instance
    .setExecutor(...) // Set your own `java.util.concurrent.Executor` for building the Java HttpClient instance
    .setHttpClient(...) // Set your own Java HttpClient (if you set this, `setSSLContext`/`setSSLParameters`/`setExecutor` will have no effect)
    .setToken(...); // You can set the Consul ACL token here
ConsulClient client = new ConsulClient(b.build());

Migrating from TlsConfig to SSLContext

The com.ecwid.consul.transport.ClientUtils class contains a method createSSLContext that can allow you to migrate from your existing TlsConfig to an SSLContext. This is called internally when the ConsulRawClient is built with a TlsConfig instance, please note that SSL hostname verification and certificate validation are disabled when using this option. Please use your own SSLContext to support hostname verification and certificate validation.

TlsConfig tlsCfg = ...;
SSLContext sslCtx = ClientUtils.createSSLContext(tlsCfg);
// use sslCtx as needed

Making various Consul API calls

Setting the ACL token

If ACL is enabled, you will need to assign a token that will be passed within the 'X-Consul-Token' HTTP header. This token can be assigned like so:

// during client construction
ConsulRawClient.Builder b = ...;
ConsulClient client = new ConsulClient(b.build(), "my-consul-acl-token"); // passing as CharSequence (less secure method)
// or...
char[] consulAclToken = ...;
ConsulClient client = new ConsulClient(b.build(), consulAclToken); // passing as char[] (preferred, more secure method)


// after client construction
ConsulClient client = ...;
consul.setToken("my-consul-acl-token"); // passing as CharSequence (less secure method)
// or...
char[] consulAclToken = ...;
consul.setToken(consulAclToken); // passing as char[] (preferred, more secure method)

It is preferrable to pass the Consul ACL token as a char[] to prevent String-pooling but the CharSequence method is kept for compatibility purposes.

Consul KV API

To make calls to the Consul KV Store API:

// set KV
byte[] binaryData = new byte[] {1,2,3,4,5,6,7};
client.setKVBinaryValue("someKey", binaryData);

client.setKVValue("com.my.app.foo", "foo");
client.setKVValue("com.my.app.bar", "bar");
client.setKVValue("com.your.app.foo", "hello");
client.setKVValue("com.your.app.bar", "world");

// get single KV for key
Response<GetValue> keyValueResponse = client.getKVValue("com.my.app.foo");
System.out.println(keyValueResponse.getValue().getKey() + ": " + keyValueResponse.getValue().getDecodedValue()); // prints "com.my.app.foo: foo"

// get list of KVs for key prefix (recursive)
Response<List<GetValue>> keyValuesResponse = client.getKVValues("com.my");
keyValuesResponse.getValue().forEach(value -> System.out.println(value.getKey() + ": " + value.getDecodedValue())); // prints "com.my.app.foo: foo" and "com.my.app.bar: bar"

Consul Catalog API

To make calls to the Consul Catalog API:

//list known datacenters
Response<List<String>> response = client.getCatalogDatacenters();
System.out.println("Datacenters: " + response.getValue());

Consul Agent API

To make calls to the Consul Agent API:

// register new service
NewService newService = new NewService();
newService.setId("myapp_01");
newService.setName("myapp");
newService.setTags(Arrays.asList("EU-West", "EU-East"));
newService.setPort(8080);
client.agentServiceRegister(newService);

// register new service with associated health check
NewService newService = new NewService();
newService.setId("myapp_02");
newService.setTags(Collections.singletonList("EU-East"));
newService.setName("myapp");
newService.setPort(8080);

NewService.Check serviceCheck = new NewService.Check();
serviceCheck.setScript("/usr/bin/some-check-script");
serviceCheck.setInterval("10s");
newService.setCheck(serviceCheck);

client.agentServiceRegister(newService);

Consul Health API

To make calls to the Consul Health API:

// query for healthy services based on name (returns myapp_01 and myapp_02 if healthy)
HealthServicesRequest request = HealthServicesRequest.newBuilder()
					.setPassing(true)
					.setQueryParams(QueryParams.DEFAULT)
					.build();
Response<List<HealthService>> healthyServices = client.getHealthServices("myapp", request);

// query for healthy services based on name and tag (returns myapp_01 if healthy)
HealthServicesRequest request = HealthServicesRequest.newBuilder()
					.setTag("EU-West")
					.setPassing(true)
					.setQueryParams(QueryParams.DEFAULT)
					.build();
Response<List<HealthService>> healthyServices = client.getHealthServices("myapp", request);