Git Product home page Git Product logo

consul-client's Introduction

Build Status Download Maven Central

Consul Client for Java

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

Installation

Note

As of 1.0.0, this library requires Java 8.

Note

In 0.13.x, both shaded and non-shaded JARs are provided. The shaded JAR has a shaded classifier, while the non-shaded JAR has no classifier. Note that this is a change from 0.12 and 0.11.

In 0.11.X and 0.12.x, the Consul JAR is a shaded JAR, with most dependencies included. This was done because a number of issues being files were related to dependency conflicts. The JAR is a bit bigger, but the HTTP + JSON libraries are now internal to the JAR. Only Guava is still a transitive dependency.

Bintray:

Grab the latest binary (1.1.1) here.

Gradle:

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

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

Maven:

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

<repositories>
    <repository>
        <snapshots>
            <enabled>false</enabled>
        </snapshots>
        <id>central</id>
        <name>bintray</name>
        <url>http://jcenter.bintray.com</url>
    </repository>
</repositories>

Basic Usage

Example 1: Register and check your service in with Consul.

Consul consul = Consul.builder().build(); // 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(serviceId); // check in with Consul, serviceId required only.  client will prepend "service:" for service level checks.
// Note that you need to continually check in before the TTL expires, otherwise your service's state will be marked as "critical".

Example 2: Find available (healthy) services.

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

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

Example 3: Store key/values.

Consul consul = Consul.builder().build(); // 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.

A blocking is used to wait for a potential changes in the key value store.

// Set a read timeout to a larger value then we will block.
Consul consul = Consul.builder()
    .withReadTimeoutMillis(TimeUnit.SECONDS.toMillis(315))
    .build();
final KeyValueClient kvClient = consul.keyValueClient();

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

ConsulResponseCallback<Optional<Value>> callback = new ConsulResponseCallback<Optional<Value>>() {

    AtomicReference<BigInteger> index = new AtomicReference<BigInteger>(null);

    @Override
    public void onComplete(ConsulResponse<Optional<Value>> consulResponse) {

        if (consulResponse.getResponse().isPresent()) {
            Value v = consulResponse.getResponse().get();
            LOGGER.info("Value is: {}", v.getValue());
        }

	index.set(consulResponse.getIndex());
        watch();
    }

    void watch() {
        kvClient.getValue("foo", QueryOptions.blockMinutes(5, index.get()).build(), this);
    }

    @Override
        public void onFailure(Throwable throwable) {
            LOGGER.error("Error encountered", throwable);
            watch();
        }
    };

    kvClient.getValue("foo", QueryOptions.blockMinutes(5, new BigInteger("0")).build(), callback);

Example 5: Subscribe to healthy services

You can also use the ConsulCache implementations to easily subscribe to healthy service changes or Key-Value changes.

Agent agent = client.agentClient().getAgent();
String serviceName = "my-service";

ServiceHealthCache svHealth = ServiceHealthCache.newCache(healthClient, serviceName);

svHealth.addListener(new ConsulCache.Listener<HostAndPort, ServiceHealth>() {
    @Override
    public void notify(Map<HostAndPort, ServiceHealth> newValues) {
        // do Something with updated server map
    }
});
svHealth.start();

Example 6: Find Raft peers.

StatusClient statusClient = Consul.builder().build().statusClient();

for(String peer : statusClient.getPeers()) {
	System.out.println(peer); // 127.0.0.1:8300
}

Example 7: Find Raft leader.

StatusClient statusClient = Consul.builder().build().statusClient();

System.out.println(statusClient.getLeader()); // 127.0.0.1:8300

Development Notes

consul-client makes use of immutables to generate code for many of the value classes. This provides a lot of functionality and benefit for little code, but it does require some additional development setup.

Official instructions are here, although you may want to change the target directories to the more gradle-like "generated/source/apt/main" and "generated/source/apt/test" targets.

Integration Tests

Integrations Tests rely on the assumption that a Consul server is running on localhost's default port 8500.

You can run a Consul server in docker using the following command line:

docker kill dev-consul ; docker rm dev-consul ; docker run -d -p 127.0.0.1:8500:8500 --name=dev-consul consul

Eclipse-specific notes

Their instructions for eclipse a bit difficult to grok, but I was able to get eclipse to compile by following the second part of the instructions. Essentially, enable annotation processing, then extend the M2_REPO variable to include the immutables annotation processor. One thing is that documentation is out of date in that it tells you the wrong jar to include - it should be org/immutables/value/2.0.16/value-2.0.16.jar.

extending M2_REPO

IntelliJ-specific notes

One caveat found using IntelliJ is that you must mark your source directory as a "Generated sources root" for IntelliJ to add the contents to your classpath. For example, if you setup your target directory as "generated/source/apt/main", right-click on the 'main' subfolde and click "Mark Directory as -> Generated sources root".

Another issue is that upon changes to the build.gradle file or reimporting the gradle project, the "sources root" designation may be cleared, and it will need to be re-marked.

consul-client's People

Contributors

rickfast avatar yfouquet avatar cschroedl-gov avatar adericbourg avatar jplock avatar yannrobert avatar odiszapc avatar maqdev avatar weberr13 avatar lburgazzoli avatar alesharik avatar vascokk avatar robinmeiss avatar hrmohr avatar alugowski avatar isuftin avatar thongsav-usgs avatar jeinwag avatar robbert229 avatar killerwhile avatar art4noir avatar shuraa avatar xiuwyang avatar timboven avatar maxixcom avatar dnance avatar yashvyas avatar trevorr avatar suvitruf avatar shays10 avatar

Watchers

James Cloos avatar Marcelo Vicente Pesenti Fachinelli avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.