Distributed-zookeeper-代码

参考资料

必看:https://www.cnblogs.com/leesf456/p/6028416.html
必看:https://www.cnblogs.com/ainima/p/6331693.html
必看:https://yq.aliyun.com/articles/71870?utm_campaign=wenzhang&utm_medium=article&utm_source=QQ-qun&201738&utm_content=m_12834
必看:https://www.cnblogs.com/fanguangdexiaoyuer/p/7077520.html

ZkClient必看:https://www.cnblogs.com/shay-zhangjin/p/7781017.html

代码

  • 主线程连接Zookeeper服务端,但这个过程是异步的。会话的生命周期是“CONNECTING”。
  • await方法阻塞主线程。等待服务端的返回。
  • 主线程连接Zookeeper服务端时,注册了一个Watcher。该Watcher返回WatchedEvent事件。当连接成功时,countDown方法执行,解除主线程的阻塞状态。主线程继续执行后续代码。
package com.everyday.helloworld.zookeeper;

import java.util.concurrent.CountDownLatch;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;


public class ZookeeperConnect1 implements Watcher {

    private static CountDownLatch countDownLatch = new CountDownLatch(1);

    @Override
    public void process(WatchedEvent event) {
        System.out.println("Receive event:" + event);
        if (Event.KeeperState.SyncConnected == event.getState()) {
            try {
                Thread.sleep(3000L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("countDown-----------");
            countDownLatch.countDown();
        }
    }

    public static void main(String[] args) throws Exception {
        ZooKeeper zooKeeper = new ZooKeeper("192.168.198.100:2181", 5000, new ZookeeperConnect1());
        System.out.println("zooKeeper.getState()=" + zooKeeper.getState());

        countDownLatch.await();
        System.out.println("after countDownLatch.await()");
    }
}

猜你喜欢

转载自blog.csdn.net/yulong1026/article/details/80888679