Leader election with Consul


Step 1. Add the JitPack repository to your build file

Add it in your root build.gradle at the end of repositories:

	dependencyResolutionManagement {
		repositories {
			maven { url '' }

Add it in your build.sbt at the end of resolvers:

    resolvers += "jitpack" at ""

Add it in your project.clj at the end of repositories:

    :repositories [["jitpack" ""]]

Step 2. Add the dependency

	dependencies {
		implementation 'com.github.kinguinltdhk:leadership-consul:0.3.1'

    libraryDependencies += "com.github.kinguinltdhk" % "leadership-consul" % "0.3.1"

    :dependencies [[com.github.kinguinltdhk/leadership-consul "0.3.1"]]


Leadership Consul


Look into releases section and pick version.

Put into Your

repositories {
    // ...
    maven { url "" }

dependencies {
    // ...
    compile "com.github.kinguinltdhk:leadership-consul:0.2.0"

Example of plain Java usage

Use SimpleClusterFactory to build() Your Gambler instance. Every Gambler implementation provides asObservable() which facilitate access to events by subscribers. This code will create ActiveGambler and subscribe to it with simple console output printer and print Gambler events.

You should see in the output:

elected // after 5 sconds
elected.first // after 5 sconds
elected // every 10 seconds

Notice: Execution of this code require Consul to be available on localhost:8500.

new SimpleClusterFactory()
    .subscribe(n -> System.out.println(n));

Spring example

@EnableConfigurationProperties(value = {ClusterProperties.class, ConsulProperties.class})
public class MultiInstance {
    private ClusterProperties clusterProperties;

    private ConsulProperties consulProperties;

    public SessionConsulClient sessionConsulClient() {
        return new SessionConsulClient(consulProperties.getHost(), consulProperties.getPort());

    public KeyValueConsulClient keyValueConsulClient() {
        return new KeyValueConsulClient(consulProperties.getHost(), consulProperties.getPort());

    public Gambler multiinstance(SessionConsulClient sessionConsulClient, KeyValueConsulClient keyValueConsulClient) {
        return new SimpleClusterFactory(sessionConsulClient, keyValueConsulClient)

Note: Above configuration only works when Consul is enabled cause of @ConditionalOnConsulEnabled. You can remove this annotation.


@ConfigurationProperties(prefix = "cluster")
public class ClusterProperties {
    private ClusterConfiguration leader;

    public ClusterConfiguration getLeader() {
        return leader;

    public void setLeader(ClusterConfiguration leader) {
        this.leader = leader;

In application.yml put section:

        serviceName: cluster
        serviceId: node-1
            host: localhost
            port: 8500
            ttl: 15
            refresh: 7
            envelopeTemplate: services/%s/leader