Skip to content
This repository was archived by the owner on Jul 27, 2023. It is now read-only.

rickfast/consul-client

Repository files navigation

Build Status

Consul Client for Java

Simple client for the Consul HTTP API. For more information about the Consul HTTP API, go here.

Installation

###Bintray:

Grab the latest binary (0.4) here.

###Gradle:

Note: Maven Central inclusion pending. Should be available soon.

repositories {
    jcenter() // or mavenCentral()
}

dependencies {
    compile 'com.orbitz.consul:consul-client:0.4'
}

###Maven:

<dependencies>
    <dependency>
        <groupId>com.orbitz.consul</groupId>
        <artifactId>consul-client</artifactId>
        <version>0.4</version>
    <dependency>
<dependencies>

Basic Usage

Example 1: Register and check your service in with Consul. Note that you need to continually check in before the TTL expires, otherwise your service's state will be marked as "critical".

Consul consul = Consul.newClient(); // connect to Consul on localhost
AgentClient agentClient = consul.agentClient();

String serviceName = "MyService";
String serviceId = "1";

agentClient.register(8080, 3L, serviceName, serviceId); // registers with a TTL of 3 seconds
agentClient.pass(); // check in with Consul

Example 2: Find available (healthy) services.

Consul consul = Consul.newClient(); // connect to Consul on localhost
HealthClient healthClient = consul.healthClient();

<List<ServiceHealth> nodes = healthClient.getHealthyNodes("DataService").getResponse(); // discover only "passing" nodes

Example 3: Store key/values.

Consul consul = Consul.newClient(); // connect to Consul on localhost
KeyValueClient kvClient = consul.keyValueClient();

kvClient.putValue("foo", "bar");

String value = kvClient.getValueAsString("foo").get(); // bar

Example 4: Blocking call for value.

import static com.orbitz.consul.option.QueryOptionsBuilder;

Consul consul = Consul.newClient();
KeyValueClient kvClient = consul.keyValueClient();

kvClient.putValue("foo", "bar");

Value value = kvClient.getValue("foo", builder().blockMinutes(10, 120).build()).get(); // will block (long poll) for 10 minutes or until "foo"'s value changes.