io.tarantool.driver.cluster.AbstractDiscoveryClusterAddressProvider Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of cartridge-driver Show documentation
Show all versions of cartridge-driver Show documentation
Tarantool Cartridge driver for Tarantool versions 1.10+ based on Netty framework
package io.tarantool.driver.cluster;
import io.tarantool.driver.TarantoolClusterAddressProvider;
import io.tarantool.driver.core.TarantoolDaemonThreadFactory;
import io.tarantool.driver.TarantoolServerAddress;
import io.tarantool.driver.exceptions.TarantoolClientException;
import java.util.Collection;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
/**
* Base class offering discovery task creation and updating of the internal collection of addresses
*
* @author Alexey Kuzin
*/
public abstract class AbstractDiscoveryClusterAddressProvider implements TarantoolClusterAddressProvider {
private final TarantoolClusterDiscoveryConfig discoveryConfig;
private final ScheduledExecutorService scheduledExecutorService;
private final CountDownLatch initLatch = new CountDownLatch(1);
private final AtomicReference> addressesHolder = new AtomicReference<>();
public AbstractDiscoveryClusterAddressProvider(TarantoolClusterDiscoveryConfig discoveryConfig) {
this.discoveryConfig = discoveryConfig;
this.scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(
new TarantoolDaemonThreadFactory("tarantool-discovery"));
}
protected void startDiscoveryTask() throws TarantoolClientException {
Runnable discoveryTask = () -> {
try {
Collection addresses = discoverAddresses();
setAddresses(addresses);
} finally {
if (initLatch.getCount() > 0) {
initLatch.countDown();
}
}
};
this.scheduledExecutorService.scheduleWithFixedDelay(
discoveryTask,
0,
discoveryConfig.getServiceDiscoveryDelay(),
TimeUnit.MILLISECONDS
);
}
protected TarantoolClusterDiscoveryConfig getDiscoveryConfig() {
return discoveryConfig;
}
protected ScheduledExecutorService getExecutorService() {
return scheduledExecutorService;
}
protected abstract Collection discoverAddresses();
private void setAddresses(Collection addresses) {
this.addressesHolder.set(addresses);
}
@Override
public Collection getAddresses() {
try {
initLatch.await();
} catch (InterruptedException e) {
throw new TarantoolClientException("Interrupted while waiting for cluster addresses discovery");
}
return addressesHolder.get();
}
@Override
public void close() {
if (scheduledExecutorService != null) {
scheduledExecutorService.shutdownNow();
}
}
}