1. 程式人生 > >zookeeper增刪改查與監聽API

zookeeper增刪改查與監聽API


//監聽單節點內容
public class WatchDemo{
	public static void main(String[] args) throws Exception {
		private String connectString="ip1:2181,ip2:2181,ip3:2181";
		private int sessionTimeout = 3000;

		ZooKeeper zkCli = new ZooKeeper(connectString,sessionTimeout,new Watcher(){
			@Override
			public void process(WatchedEvent event){

			}
		});

		byte[] data = zkCli.getData("/", new Watcher(){
			@Override
			public void process(WatchedEvent event){
				System.out.println("監聽路徑為"+event.getPath());
				System.out.println("監聽的型別"+event.getType());
				System.out.println("資料被2貨修改了!!!!!!");
			}
		}, null);//第三個引數為狀態

		System.out.println(new String(data));

		Thread.sleep(Long.MAX_VALUE);
	}
}

監聽目錄
public class WatchDemo1{
	public static void main(String[] args) throws Exception {
		private String connectString="ip1:2181,ip2:2181,ip3:2181";
		private int sessionTimeout = 3000;
		static List<String> children = null;

		ZooKeeper zkCli = new ZooKeeper(connectString,sessionTimeout,new Watcher(){
			@Override
			public void process(WatchedEvent event){
				System.out.println("正在監聽中");
			}
		});

		//監聽目錄
		children = zkCli.getChildren("/", new Watcher(){
			@Override
			public void process(WatchedEvent event){
				System.out.println("監聽路徑為"+event.getPath());
				System.out.println("監聽的型別"+event.getType());
				System.out.println("資料被2貨修改了!!!!!!");
				for(String c : children){
					System.out.println(c);
				}
			}
		});
		Thread.sleep(Long.MAX_VALUE);
		//為了讓他阻塞執行緒,還是一次監聽
}