packagecom.amber;import org.apache.zookeeper.*;importorg.apache.zookeeper.data.Stat;importjava.io.IOException;public classZookeeperWatchDemo {privateZooKeeper zookeeper;private String oldValue = "";private String newValue = "";public ZooKeeper zkConnect( ) throwsIOException {
String path= "127.0.0.1:2181";
zookeeper= new ZooKeeper(path, 20 * 1000, null);returnzookeeper;
}public void createZnode(String path, byte[] value, Watcher watcher, CreateMode node ) throwsKeeperException, InterruptedException {
zookeeper.create(path, value, ZooDefs.Ids.OPEN_ACL_UNSAFE, node);
}public String getZnodeValue(final String path ) throwsKeeperException, InterruptedException {byte[] data = zookeeper.getData(path, newWatcher() {
@Overridepublic voidprocess(WatchedEvent watchedEvent) {
triggerWatch(path);
}
},newStat());
oldValue= newString(data);return newString(data);
}public booleantriggerWatch (String path) {byte[] data = new byte[0];try{
data= zookeeper.getData(path, newWatcher() {
@Overridepublic voidprocess(WatchedEvent watchedEvent) {
triggerWatch(path);
}
},newStat());
}catch(KeeperException e) {
e.printStackTrace();
}catch(InterruptedException e) {
e.printStackTrace();
}
newValue= newString(data);if(oldValue.equals(newValue)) {
System.out.println("on change");return false;
}else{
System.out.println("oldvalue: " + oldValue + "new value: " +newValue);
oldValue=newValue;return true;
}
}public static void main(String[] args) throwsIOException, KeeperException, InterruptedException {//创建
ZookeeperWatchDemo zookeeperWatchDemo = newZookeeperWatchDemo();
ZooKeeper zooKeeper=zookeeperWatchDemo.zkConnect();
String path= "/amberas";
String value= "hahahahaha";if (zooKeeper.exists(path, false) == null) {
zookeeperWatchDemo.createZnode(path, value.getBytes(),null, CreateMode.PERSISTENT);
}
String znodeValue=zookeeperWatchDemo.getZnodeValue(path);
System.out.println(znodeValue);
Thread.sleep(1000 * 60 * 50);
}
}