zookeeper-JAVA-API调用

一、
导入 JAR包
解压zookeeper安装包
lib 目录下的面的JAR+zookeeper.jar
新建 zookeeper的JAVA工程
新建 lib 文件夹,复制JAR包至lib文件夹中
全选 JAR,右键 --> build path --> add

二、

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

import org.apache.zookeeper.KeeperException;
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 ZkDemo {

	/**
	 * @param args
	 * @throws IOException 
	 * @throws InterruptedException 
	 * @throws KeeperException 
	 */
	public static void main(String[] args) throws IOException, InterruptedException, KeeperException {

		// 内部类调用外部类的变量,变量需为 final 
		final CountDownLatch count = new CountDownLatch(1);
		// 1.创建会话
		String connectString = "192.168.76.131:2181,192.168.76.134:2181,192.168.76.132:2181" ;
		final ZooKeeper zookeeper = new ZooKeeper(connectString, 5000, new Watcher() {
			
			public void process(WatchedEvent event) {
				// 确保连接状态成功
				// 方法:使用 countDownLatch 
				if(event.getState() == KeeperState.SyncConnected){
					count.countDown();
				}
			}
		});
		// 由于调用了 countDown() 方法,所以在当前计数到达零之前,await 方法会一直受阻塞
		count.await();
		
		// 2.
		// 创建节点:同步方式,会发生阻塞,只有创建成功之后,程序才会执行下去
//		String create = zookeeper.create("/park", "abcd".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
//		System.out.println(create);
		// 返回创建节点信息
		
		// 创建节点:异步方式,程序不阻塞,但执行完毕后,不保证节点创建成功
//		zookeeper.create("/park2", "abcd".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT, new StringCallback() {
//			
//			public void processResult(int rc, String path, Object ctx, String name) {
//				System.out.println("创建完毕:节点名称:"+name);
//			}
//		}, null);
//		while(true){
			// 什么都不做;添加原因是:异步创建节点,只有SYSO执行后才是创建成功,
			// 因为是异步执行,所以程序会继续执行下去,但因为下面无代码可执行了,程序结束了
			// 所以SYSO无输出,但节点已创建完毕
//		}
		
		// 3.删除
		// 同步方法:version:-1 匹配任务版本
//	    zookeeper.delete("/park2", -1);
		// 异步方法:		
//		zookeeper.delete("/park", -1, new VoidCallback() {
//			
//			public void processResult(int rc, String path, Object ctx) {
//				System.out.println("删除完毕:路径名称:"+path);
//			}
//		}, null);
//		while(true){}
		
		// 4.读取-子节点
//		List<String> children = zookeeper.getChildren("/", new Watcher() {
//			
//			public void process(WatchedEvent event) {
//				if(event.getType() == EventType.NodeChildrenChanged){
//					try {
//						// 运行;在虚拟机中执行 zkCli.sh create /park 
//						// 节点发生变化,控制台打印输出当前所有节点
//						// 只能监控一次变化,再次创建则无效
//						List<String> list = zookeeper.getChildren("/", false);
//						for(String s : list){
//							System.out.println(s);
//						}
//					} catch (KeeperException e) {
//						e.printStackTrace();
//					} catch (InterruptedException e) {
//						e.printStackTrace();
//					}
//				}
//			}
//		});
//		for(String s : children){
//			System.out.println(s);
//		}
//		while(true){
//			
//		}
		
		
	}

}


多次变化,均可监控到
create /aaa xxx
create /bbb xxx
delete /aaa

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

import org.apache.zookeeper.AsyncCallback.DataCallback;
import org.apache.zookeeper.AsyncCallback.StatCallback;
import org.apache.zookeeper.KeeperException;
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;
import org.apache.zookeeper.data.Stat;

public class ZkDemo1 {

	private static ZooKeeper zookeeper = null ;

	public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
		
		final CountDownLatch count = new CountDownLatch(1);
		String connectString = "192.168.76.131:2181,192.168.76.134:2181,192.168.76.132:2181" ;
		zookeeper = new ZooKeeper(connectString, 5000, new Watcher() {
			
			public void process(WatchedEvent event) {
				if(event.getState() == KeeperState.SyncConnected){
					count.countDown();
				}
				
				// 5.获取节点数据,当数据发生变化时
				if(event.getType() == EventType.NodeDataChanged){
					String path = event.getPath();
					System.out.println(path+"节点数据发生变化");
					try {
						byte[] datas = zookeeper.getData(path, true, null);
						System.out.println("变化后的数据:"+new String(datas));
					} catch (KeeperException e) {
						e.printStackTrace();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				
				// 7.节点创建或删除时打印
				if(event.getType() == EventType.NodeCreated ||
						event.getType() == EventType.NodeDeleted){
					String path = event.getPath();
					try {
						Stat stat = zookeeper.exists(path, true);
						System.out.println(stat);
					} catch (KeeperException e) {
						e.printStackTrace();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		});
		count.await();
		// 4.获取 childrenNode
//		List<String > list = zookeeper.getChildren("/", new ChildrenWatcher());
//		for(String s : list){
//			System.out.println(s);
//		}
		
		// 5.获取节点数据
		// 同步
		byte[] datas = zookeeper.getData("/poi", true, null);
		System.out.println(new String(datas));
		
		// 异步
		zookeeper.getData("/park", true, new DataCallback() {
			
			public void processResult(int rc, String path, Object ctx, byte[] data,
					Stat stat) {
				System.out.println(new String(data));
			}
		}, null);
		
		// 6.更新数据
		zookeeper.setData("/poi", "2222222".getBytes(), -1);
		zookeeper.setData("/park", "33333333".getBytes(), -1, new StatCallback() {
			
			public void processResult(int rc, String path, Object ctx, Stat stat) {
				System.out.println("path:"+path+"stat:"+stat);
			}
		}, null);
		
		// 7.节点是否存在
		Stat exist = zookeeper.exists("/parkx", true);
		System.out.println(exist);
		while(true){}
	}

	static class ChildrenWatcher implements Watcher{
		
		public void process(WatchedEvent event) {
			
			if(event.getType() == EventType.NodeChildrenChanged){
				
				List<String> childrenList = null ;
				try {
					// 后续的数据变更,有 Watcher 进行监控输出
					childrenList = zookeeper.getChildren("/", new ChildrenWatcher());
				} catch (KeeperException e) {
					e.printStackTrace();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				for(String s : childrenList){
					System.out.println(s);
				}
			}
		}
		
	}
}

猜你喜欢

转载自mingyundezuoan.iteye.com/blog/2371214