CountDownLatch的监听异步回调成功应用

2022-04-13 15:45:27 浏览数 (1)

通过CountDownLatch 实现等待zookeeper连接建立完毕后,代码再向后执行的逻辑。

代码语言:javascript复制
package com.wolf.cache.zk;


import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

@Slf4j
public class ZookeeperSession {

    private static CountDownLatch connectedSemaphore = new CountDownLatch(1);

    private ZooKeeper zooKeeper;

    private ZookeeperSession(){
        // 去连接zookeeper server, 创建会话的时候,是异步进行的
        // 所有要给一个监听器,说告诉我们什么时候是真正的完成跟zookeeper server 连接
        try {
            this.zooKeeper = new ZooKeeper("192.168.43.10:2181,192.168.43.11:2181,192.168.43.12:2181",
                    5000,
                    new ZookeeperWather());
            log.info("### zookeeper server 连接成功, state={} ###", zooKeeper.getState());

            connectedSemaphore.await();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private class ZookeeperWather implements Watcher {

        @Override
        public void process(WatchedEvent watchedEvent) {
            if (Event.KeeperState.SyncConnected == watchedEvent.getState()) {
                connectedSemaphore.countDown();
            }
        }
    }

    private static class SingleTon {
        private static ZookeeperSession instance = new ZookeeperSession();

        public static ZookeeperSession getInstance() {
            return SingleTon.instance;
        }
    }

    public static ZookeeperSession getInstance() {
        return SingleTon.getInstance();
    }

    public static void init() {
        getInstance();
    }

}

0 人点赞