ZooKeeper建立会话

ZooKeeper万事的开始建立会话

由于ZooKeeper客户端和服务端建立会话是一个异步过程,所以在建立会话时需要用到ZooKeeper监听机制即“org.apache.zookeeper.Watcher”接口,和“java.util.concurrent.CountDownLatch”类,控制阻塞和同步,对于CountDownLatch不了解的看官可以百度一下啦。

package zkapitest;

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

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.EventType;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooKeeper;

public class CreateSession {

	public static void main(String[] args) {
		try {
			ZooKeeper zookeeper = new ZKClient().getZooKeeper();
			System.out.println(zookeeper.getSessionId());
		} catch (IOException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

}

/**
 * ZooKeeper工具类 实现Watcher接口
 *
 * @CreateTime 2016-1-25下午8:25:39
 *
 * @Vsersion 1.0
 */
class ZKClient implements Watcher {
	private CountDownLatch connectedSemaphore = new CountDownLatch(1);//定义阻塞线程,计数器为1
	private ZooKeeper zookeeper = null;
	private static String URL = "192.168.0.203:2181";//服务地址
	
	public ZooKeeper getZooKeeper() throws IOException, InterruptedException{
		zookeeper = new ZooKeeper(URL, 5000, this);
		connectedSemaphore.await();//线程阻塞
		return zookeeper;
	}
	
	public ZooKeeper getZooKeeper(long sessionId, byte[] sessionPW) throws IOException, InterruptedException{
		zookeeper = new ZooKeeper(URL, 5000, this, sessionId, sessionPW);
		connectedSemaphore.await();//线程阻塞
		return zookeeper;
	}
	
	@Override
	public void process(WatchedEvent event) {
		if (KeeperState.SyncConnected == event.getState()) {
			if(event.getType() == EventType.None && null == event.getPath()){
				connectedSemaphore.countDown();//释放线程、技术减一
			}
		} 
	}
}


你可能感兴趣的:(zookeeper)