Zookeeper API JAVA 解析

常用方法:

  • new ZooKeeper()构造方法
  • create
  • exists
  • getChildren
  • getData
注意点:
watcher 的触发,为一次性。


测试程序
package zookeeper;

import java.io.IOException;
import java.util.List;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;

public class ZookeeperTest {

	public static final int Zookeeper_SESSION_TIMEOUT = 20000;

	static ZooKeeper zk;

	static class TestWatcher implements Watcher {

		@Override
		public void process(WatchedEvent event) {
			// TODO Auto-generated method stub
			System.out.println("come from TestWatcher-> process");
		}

	}

	static TestWatcher watcher = new TestWatcher();

	/**
	 * new ZooKeeper
	 * 初始化 ZooKeeper 实例
	 */
	public static void createZKInstance() throws IOException, KeeperException,
			InterruptedException {
		zk = new ZooKeeper("ip:port,ip:port", Zookeeper_SESSION_TIMEOUT,watcher);
	}
	
	/**
	 * create
	 * 创建节点
	 */
	public static void createNode(String node) throws IOException, InterruptedException,KeeperException
	 {
	  if (zk.exists(node, null) == null) {
	   zk.create(node,node.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
	  }
	 }
	
	/**
	 * exists
	 * 判断节点是否存在
	 */
	public  static boolean isExists(String node) throws InterruptedException,
	   KeeperException {
	  if (zk.exists(node, null) == null) {
	   return false;
	  }
	  return true;
	 }
	
	/**
	 * getChildren
	 * 获取一个节点的子节点列表
	 */
	public static List<String> getChildren(String node) throws KeeperException, InterruptedException{
		return zk.getChildren(node, null);
	}
	
	/**
	 * 返回节点的数据
	 */
	public static byte[] getDate(String path ) throws KeeperException, InterruptedException{
		return zk.getData(path, null, null);
	}
	
	public static void main(String[] args) {
		try {
			createZKInstance();
			
			createNode("/testnodes");
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (KeeperException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

}


Zookeeper API JAVA 解析,布布扣,bubuko.com

Zookeeper API JAVA 解析

上一篇:走进C++程序世界----STL标准库


下一篇:C语言利用字符串数组读取字符串的误区