Search in sources :

Example 6 with LeaderSelector

use of org.apache.curator.framework.recipes.leader.LeaderSelector in project rocketmq-externals by apache.

the class RocketMQRedisReplicator method open.

@Override
public void open() throws IOException {
    if (this.replicator instanceof RedisSocketReplicator) {
        boolean single = configure.getString(DEPLOY_MODEL).equals(DEPLOY_MODEL_SINGLE);
        if (single) {
            this.replicator.open();
        } else {
            String address = configure.getString(CONFIG_PROP_ZK_ADDRESS);
            final CuratorFramework client = newClient(address, new ExponentialBackoffRetry(1000, 3));
            client.start();
            String path = ROOT_DIR + "/" + uri.getHost() + "-" + uri.getPort();
            final LeaderSelector selector = new LeaderSelector(client, path, new LeaderSelectorListenerAdapter() {

                @Override
                public void takeLeadership(final CuratorFramework client) throws Exception {
                    RocketMQRedisReplicator.this.addCloseListener(new CloseListener() {

                        @Override
                        public void handle(Replicator replicator) {
                            client.close();
                        }
                    });
                    replicator.open();
                }
            });
            selector.start();
        }
    } else {
        this.replicator.open();
    }
}
Also used : CuratorFramework(org.apache.curator.framework.CuratorFramework) ExponentialBackoffRetry(org.apache.curator.retry.ExponentialBackoffRetry) LeaderSelector(org.apache.curator.framework.recipes.leader.LeaderSelector) LeaderSelectorListenerAdapter(org.apache.curator.framework.recipes.leader.LeaderSelectorListenerAdapter) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException)

Example 7 with LeaderSelector

use of org.apache.curator.framework.recipes.leader.LeaderSelector in project BRFS by zhangnianli.

the class CuratorLeaderSelectorClient method addSelector.

/**
 * 概述:添加一个leaderSelectorLinstener
 * @param path 监听路径
 * @param id 为监听器指定一个id,如果不指定,则为空
 * @param listener 监听器
 * @user <a href=mailto:weizheng@bonree.com>魏征</a>
 */
public synchronized void addSelector(String path, String id, LeaderSelectorListener listener) {
    List<LeaderSelector> leaderSelectors = selectorMap.get(path);
    if (leaderSelectors == null) {
        leaderSelectors = new ArrayList<LeaderSelector>();
    }
    LeaderSelector leaderSelector = new LeaderSelector(client.getInnerClient(), path, listener);
    leaderSelector.setId(id);
    leaderSelector.autoRequeue();
    leaderSelectors.add(leaderSelector);
    leaderSelector.start();
    selectorMap.put(path, leaderSelectors);
}
Also used : LeaderSelector(org.apache.curator.framework.recipes.leader.LeaderSelector)

Example 8 with LeaderSelector

use of org.apache.curator.framework.recipes.leader.LeaderSelector in project Mycat_plus by coderczp.

the class DistributedSequenceHandler method initializeZK.

public void initializeZK(String zkAddress) {
    this.client = CuratorFrameworkFactory.newClient(zkAddress, new ExponentialBackoffRetry(1000, 3));
    this.client.start();
    try {
        if (client.checkExists().forPath(PATH.concat(INSTANCE_PATH)) == null) {
            client.create().creatingParentContainersIfNeeded().forPath(PATH.concat(INSTANCE_PATH));
        }
    } catch (Exception e) {
    // do nothing
    }
    this.leaderSelector = new LeaderSelector(client, PATH.concat(LEADER_PATH), this);
    this.leaderSelector.autoRequeue();
    this.leaderSelector.start();
    Runnable runnable = new Runnable() {

        @Override
        public void run() {
            try {
                while (leaderSelector.getLeader() == null) {
                    Thread.currentThread().yield();
                }
                if (!leaderSelector.hasLeadership()) {
                    isLeader = false;
                    if (slavePath != null && client.checkExists().forPath(slavePath) != null) {
                        return;
                    }
                    slavePath = client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL_SEQUENTIAL).forPath(PATH.concat("/instance/node"), "ready".getBytes());
                    while ("ready".equals(new String(client.getData().forPath(slavePath)))) {
                        Thread.currentThread().yield();
                    }
                    instanceId = Long.parseLong(new String(client.getData().forPath(slavePath)));
                    ready = true;
                }
            } catch (Exception e) {
                LOGGER.warn("Caught exception while handling zk!", e);
            }
        }
    };
    timerExecutor.scheduleAtFixedRate(runnable, 1L, 10L, TimeUnit.SECONDS);
}
Also used : ExponentialBackoffRetry(org.apache.curator.retry.ExponentialBackoffRetry) LeaderSelector(org.apache.curator.framework.recipes.leader.LeaderSelector) IOException(java.io.IOException) CancelLeadershipException(org.apache.curator.framework.recipes.leader.CancelLeadershipException)

Example 9 with LeaderSelector

use of org.apache.curator.framework.recipes.leader.LeaderSelector in project tutorials by eugenp.

the class RecipesManualTest method givenRunningZookeeper_whenUsingLeaderElection_thenNoErrors.

@Test
public void givenRunningZookeeper_whenUsingLeaderElection_thenNoErrors() {
    try (CuratorFramework client = newClient()) {
        client.start();
        LeaderSelector leaderSelector = new LeaderSelector(client, "/mutex/select/leader/for/job/A", new LeaderSelectorListener() {

            @Override
            public void stateChanged(CuratorFramework client, ConnectionState newState) {
            }

            @Override
            public void takeLeadership(CuratorFramework client) throws Exception {
            // I'm the leader of the job A !
            }
        });
        leaderSelector.start();
        // Wait until the job A is done among all the members
        leaderSelector.close();
    }
}
Also used : CuratorFramework(org.apache.curator.framework.CuratorFramework) LeaderSelectorListener(org.apache.curator.framework.recipes.leader.LeaderSelectorListener) LeaderSelector(org.apache.curator.framework.recipes.leader.LeaderSelector) ConnectionState(org.apache.curator.framework.state.ConnectionState) BaseTest(com.baeldung.apache.curator.BaseTest) Test(org.junit.Test)

Example 10 with LeaderSelector

use of org.apache.curator.framework.recipes.leader.LeaderSelector in project dble by actiontech.

the class DistributedSequenceHandler method initializeZK.

public void initializeZK(String zkAddress) {
    if (zkAddress == null) {
        throw new RuntimeException("please check zkURL is correct in config file \"myid.prperties\" .");
    }
    if (this.client != null) {
        this.client.close();
    }
    this.client = CuratorFrameworkFactory.newClient(zkAddress, new ExponentialBackoffRetry(1000, 3));
    this.client.start();
    try {
        if (client.checkExists().forPath(INSTANCE_PATH) == null) {
            client.create().creatingParentContainersIfNeeded().forPath(INSTANCE_PATH);
        }
    } catch (Exception e) {
        throw new RuntimeException("create instance path " + INSTANCE_PATH + "error", e);
    }
    this.leaderSelector = new LeaderSelector(client, KVPathUtil.getSequencesLeaderPath(), this);
    this.leaderSelector.autoRequeue();
    this.leaderSelector.start();
    Runnable runnable = new Runnable() {

        @Override
        public void run() {
            try {
                while (leaderSelector.getLeader() == null) {
                    Thread.currentThread().yield();
                }
                if (!leaderSelector.hasLeadership()) {
                    isLeader = false;
                    if (slavePath != null && client.checkExists().forPath(slavePath) != null) {
                        return;
                    }
                    slavePath = client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL_SEQUENTIAL).forPath(PATH.concat("/instance/node"), "ready".getBytes());
                    while ("ready".equals(new String(client.getData().forPath(slavePath)))) {
                        Thread.currentThread().yield();
                    }
                    instanceId = Long.parseLong(new String(client.getData().forPath(slavePath)));
                    ready = true;
                }
            } catch (Exception e) {
                LOGGER.info("Caught exception while handling zk!", e);
            }
        }
    };
    long selfCheckPeriod = 10L;
    timerExecutor.scheduleAtFixedRate(runnable, 1L, selfCheckPeriod, TimeUnit.SECONDS);
}
Also used : ExponentialBackoffRetry(org.apache.curator.retry.ExponentialBackoffRetry) LeaderSelector(org.apache.curator.framework.recipes.leader.LeaderSelector) IOException(java.io.IOException) CancelLeadershipException(org.apache.curator.framework.recipes.leader.CancelLeadershipException)

Aggregations

LeaderSelector (org.apache.curator.framework.recipes.leader.LeaderSelector)24 CuratorFramework (org.apache.curator.framework.CuratorFramework)7 LeaderSelectorListener (org.apache.curator.framework.recipes.leader.LeaderSelectorListener)6 IOException (java.io.IOException)5 ConnectionState (org.apache.curator.framework.state.ConnectionState)4 ExponentialBackoffRetry (org.apache.curator.retry.ExponentialBackoffRetry)4 CancelLeadershipException (org.apache.curator.framework.recipes.leader.CancelLeadershipException)3 LeaderSelectorListenerAdapter (org.apache.curator.framework.recipes.leader.LeaderSelectorListenerAdapter)3 Test (org.junit.Test)3 Timing (org.apache.curator.test.Timing)2 KeeperException (org.apache.zookeeper.KeeperException)2 Test (org.testng.annotations.Test)2 BaseTest (com.baeldung.apache.curator.BaseTest)1 DrUtil (com.emc.storageos.coordinator.client.service.DrUtil)1 LeaderSelectorListenerImpl (com.emc.storageos.coordinator.client.service.impl.LeaderSelectorListenerImpl)1 ReaperLeaderSelectorListener (com.emc.storageos.coordinator.client.service.impl.ReaperLeaderSelectorListener)1 URISyntaxException (java.net.URISyntaxException)1 HashMap (java.util.HashMap)1 Map (java.util.Map)1 CountDownLatch (java.util.concurrent.CountDownLatch)1