本地安装zookeeper后使用命令创建好节点以便测试:
create /mydata A1
下面就可以开始实验了,我们直接来看代码:
package com.itstyle.seckill.zookeeper;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import java.util.concurrent.CountDownLatch;
public class zkTest implements Watcher {
private static CountDownLatch countDownLatch=new CountDownLatch(1);
private static ZooKeeper zk=null;
private static Stat stat=new Stat();
public static void main(String[] args) throws Exception {
String path = "/mydata";
System.out.println("---1---");
zk = new ZooKeeper("127.0.0.1:2181",5000,new zkTest());
countDownLatch.await();
System.out.println("---4---");
byte[] data = zk.getData(path, true, stat);
String strData=new String(data);
System.out.println("--------原始数据:"+strData);
Thread.sleep(Integer.MAX_VALUE);
}
public void process(WatchedEvent watchedEvent) {
System.out.println("---2---");
String path = "/mydata";
if(Event.KeeperState.SyncConnected==watchedEvent.getState()){
if(Event.EventType.None==watchedEvent.getType()&& null==watchedEvent.getPath()){
countDownLatch.countDown();
}else if(Event.EventType.NodeDataChanged==watchedEvent.getType()){
byte[] data = new byte[0];
try {
data = zk.getData(path, true, stat);
String s = new String(data);
System.out.println("节点数据有变化:"+s);
} catch (KeeperException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
System.out.println("---3---");
}
}
---1---
---2---
---3---
---4---
--------原始数据:m4
---2---
节点数据有变化:m5
---3---
|