Zookeeper Leader選挙ツールクラス

6580 ワード

これはapache.orgの下にオープンソースのcuratorフレームワークを使用して書かれたリーダー選挙のツールクラスです.について curatorの紹介は、以下の通りです.
http://curator.apache.org/

 
本プログラムで使用するpom.xml
<org.slf4j.version>1.6.6</org.slf4j.version>
<commons-logging.version>1.1.1</commons-logging.version>
<log4j.version>1.2.14</log4j.version>
<guava.version>17.0</guava.version>
<curator-version>2.6.0</curator-version>

<!-- curator start -->
<dependency>
	<groupId>org.apache.curator</groupId>
	<artifactId>curator-recipes</artifactId>
	<version>${curator-version}</version>
</dependency>
<dependency>
	<groupId>org.apache.curator</groupId>
	<artifactId>curator-x-discovery</artifactId>
	<version>${curator-version}</version>
</dependency>
<!-- curator end -->

<dependency>
	<groupId>com.google.guava</groupId>
	<artifactId>guava</artifactId>
	<version>${guava.version}</version>
</dependency>

<dependency>
	<groupId>org.slf4j</groupId>
	<artifactId>jcl-over-slf4j</artifactId>
	<version>${org.slf4j.version}</version>
</dependency>
<dependency>
	<groupId>org.slf4j</groupId>
	<artifactId>slf4j-api</artifactId>
	<version>${org.slf4j.version}</version>
</dependency>
<dependency>
	<groupId>org.slf4j</groupId>
	<artifactId>slf4j-log4j12</artifactId>
	<version>${org.slf4j.version}</version>
</dependency>
<dependency>
	<groupId>log4j</groupId>
	<artifactId>log4j</artifactId>
	<version>${log4j.version}</version>
</dependency>

 
次はプログラムです.
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.leader.LeaderLatch;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.base.CharMatcher;

import java.util.UUID;

/**
 * <pre>
 * ZKLeaderUtils.java
 * @author kanpiaoxue<br>
 * @version 1.0
 * Create Time 2014 8 7    1:04:18<br>
 * Description : Zookeeper Leader     
 * </pre>
 */
public class ZKLeaderUtils {
    private static final Logger LOGGER = LoggerFactory
            .getLogger(ZKLeaderUtils.class);

    private ZKLeaderUtils() {
    }

    /**
     * <pre>
     * @param connectionString    Zookeeper Cluster    , :127.0.0.1:2181,127.0.0.2:2181,127.0.0.3:2181,127.0.0.4:2181,127.0.0.5:2181
     * @param leaderPath    Zookeeper       Leader       
     * @param sessionTimeoutMs     session      ,  :  。          Leader        。
     *                   ,   Leader    ,   Leader      ,    sessionTimeoutMs             Leader    ,  Leader      。
     *                   ,  Leader ZK        ,         sessionTimeoutMs   ,Leader             ZK  。      ,     Leader     Leader
     *  session    ,          Leader。    ,      :   Leader        ,     ZK              ,           ;      Leader   
     *    Leader       ,     Leader       。    Leader     。       。         sessionTimeoutMs   ,       。
     * @param connectionTimeoutMs        ,  :  
     * @param baseSleepTimeMs                    ,  :  
     * @param maxRetries                     
     * @throws Exception
     *   :    Leader
     *   :
     *        Leader ZK        ID。 ID  UUID.randomUUID()   。
     *        Leader   ,               Leader。
     *    ZK    leaderPath     ,             。
     * </pre>
     */
    public static void waitForLeader(String connectionString,
            String leaderPath, int sessionTimeoutMs, int connectionTimeoutMs,
            int baseSleepTimeMs, int maxRetries) throws Exception {
        String id = CharMatcher.anyOf("-").removeFrom(
                UUID.randomUUID().toString());
        CuratorFramework zkCient = CuratorFrameworkFactory.newClient(
                connectionString, sessionTimeoutMs, connectionTimeoutMs,
                new ExponentialBackoffRetry(baseSleepTimeMs, maxRetries));
        LOGGER.info(String.format("I'm [%s]. start to work", id));
        zkCient.start();
        zkCient.getZookeeperClient().blockUntilConnectedOrTimedOut();

        @SuppressWarnings("resource")
        LeaderLatch leaderLatch = new LeaderLatch(zkCient, leaderPath, id);
        leaderLatch.start();
        LOGGER.info("leaderLatch has startted and is waitting for being leader.");
        LOGGER.info(String.format("I'm [%s]. I think that the leader is %s",
                id, leaderLatch.getLeader()));
        leaderLatch.await();
        LOGGER.info(String.format("I'm [%s]. I'm the leader now! %s", id,
                leaderLatch.getLeader()));
    }

    public static void main(String[] args) throws Exception {

        String connectionString = "127.0.0.1:2181,127.0.0.2:2181,127.0.0.3:2181";
        String leaderPath = "/leader";
        int sessionTimeoutMs = 10 * 1000;
        int connectionTimeoutMs = 10 * 1000;
        int baseSleepTimeMs = 1;
        int maxRetries = 20000;

        waitForLeader(connectionString, leaderPath, sessionTimeoutMs,
                connectionTimeoutMs, baseSleepTimeMs, maxRetries);
        System.out.println("I'm the leader. I can do something here.")
    }

}