All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.mstream.trader.commons.config.CuratorFrameworkSupplier Maven / Gradle / Ivy

The newest version!
package io.mstream.trader.commons.config;


import io.mstream.trader.commons.config.model.Version;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import ratpack.service.Service;
import ratpack.service.StartEvent;

import javax.inject.Inject;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;

import static java.lang.String.format;
import static org.apache.curator.framework.imps.CuratorFrameworkState.STARTED;

public class CuratorFrameworkSupplier implements
        Supplier, Service {

    private final ScheduledExecutorService executor;
    private final CuratorFramework curator;

    @Inject
    public CuratorFrameworkSupplier(
            @ConnectionString String connectionString,
            @ApplicationName String applicationName,
            @Application Version applicationVersion,
            ScheduledExecutorService executor) {

        this.executor = executor;

        curator = CuratorFrameworkFactory.builder()
                .connectString(connectionString)
                .retryPolicy(new ExponentialBackoffRetry(1000, 3))
                .namespace(
                        format(
                                "config/%s/%s",
                                applicationName,
                                applicationVersion.getValue()
                        )
                )
                .build();
    }

    @Override
    public void onStart(StartEvent event) throws Exception {
        executor.scheduleAtFixedRate(
                this::startCuratorIfNeeded,
                0,
                10,
                TimeUnit.SECONDS
        );
    }

    @Override
    public CuratorFramework get() {
        startCuratorIfNeeded();
        if (!isCuratorRunning()) {
            throw new IllegalStateException("curator is not running");
        }
        return curator;
    }

    private boolean isCuratorRunning() {
        synchronized (curator) {
            return STARTED.equals(curator.getState());
        }
    }

    private void startCuratorIfNeeded() {
        if (!isCuratorRunning()) {
            synchronized (curator) {
                curator.start();
            }
        }
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy