zookeeperAPI的使用(1)创建会话

zookeeper 创建连接 (zookeeper API四种创建连接)


/**
 * zookeeper 创建连接有四种方式
 * 
 * @author Administrator
 *
 */

/*
 * 参数介绍 1. connectString zookeeper服务器列表, 
 *  a. host:port(如:192.168.1:2181)
 *  b.host:port/path(如:192.168.1:2181/zk) 之后所有操作都会基于这个路径
 * 
 * 2. sessionTimeout 回话超时时间(毫秒)
 * 
 * 3. watcher 事件通知处理(可以为null,表明不需要watcher时间通知)
 * 
 * 4. canBeReadOnly 用于标识当前回话是否"readl-only"模式(即当zookeeper发生故障时,依然能够提供读服务)
 * 
 * 5. sessionId和 sessionPasswd 代表回话ID和回话秘钥,这两个参数唯一确定一个回话,同时客户端使用这两个参数
 * 可以实现客户端回话服用,从而达到恢复会话的效果。
 * 
 */

public class Create implements Watcher {

    CountDownLatch CountDownLatch = new CountDownLatch(1);

    /**
     * 1. ZooKeeper.ZooKeeper(String connectString, int sessionTimeout, Watcher
     * watcher)
     * 
     * @throws IOException
     * @throws InterruptedException
     */
    @Test
    public void testCreate1() throws IOException, InterruptedException {
        ZooKeeper zk = new ZooKeeper(Connection.CONNECTION, 5000, new Create());
        System.out.println(zk);
        CountDownLatch.await();
    }

    /**
     * 2. ZooKeeper(String connectString, int sessionTimeout, Watcher watcher,
     * boolean canBeReadOnly) watcher)
     * 
     * @throws IOException
     * @throws InterruptedException
     */
    @Test
    public void testCreate2() throws IOException, InterruptedException {
        ZooKeeper zk = new ZooKeeper(Connection.CONNECTION, 5000, new Create(), true);
        System.out.println(zk);
        CountDownLatch.await();
    }

    /**
     * 3. ZooKeeper(String connectString, int sessionTimeout, Watcher watcher, long
     * sessionId, byte[] sessionPasswd)
     * 
     * @throws IOException
     * @throws InterruptedException
     */
    @Test
    public void testCreate3() throws IOException, InterruptedException {
        ZooKeeper zk = new ZooKeeper(Connection.CONNECTION, 5000, new Create(), 111l, "root".getBytes());
        System.out.println(zk);
        CountDownLatch.await();
    }

    /**
     * 4. ZooKeeper(String connectString, int sessionTimeout, Watcher watcher, long
     * sessionId, byte[] sessionPasswd, boolean canBeReadOnly)
     * 
     * @throws IOException
     * @throws InterruptedException
     */
    @Test
    public void testCreate4() throws IOException, InterruptedException {
        ZooKeeper zk = new ZooKeeper(Connection.CONNECTION, 5000, new Create(), 111l, "root".getBytes(), true);
        System.out.println(zk);
        CountDownLatch.await();

    }

    @Override
    public void process(WatchedEvent event) {
        System.out.println("processing.............");
        System.out.println(event);
        CountDownLatch.countDown();
    }

}

你可能感兴趣的:(zookeeper,分布式)