1 Create a Demo Class and run
import java.io.IOException;
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.ZooKeeper;
public class ZoomkeepTest2 {
// 创建一个与服务器的连接
ZooKeeper zk = null;
public ZoomkeepTest2() {
try {
zk = new ZooKeeper("127.0.0.1:2181", 500000, new WatcherImpl());
// zk.getData("/zk-demo/watch-this", true, null);
while (true) {
}
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭连接
if (null != zk) {
try {
zk.close();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class WatcherImpl implements Watcher {
public void process(WatchedEvent event) {
System.out.println("已经触发了" + event.getType() + "事件!");
if (event.getType().equals(EventType.NodeDataChanged)) {
try {
System.out.println(new String(zk.getData("/zk-demo/watch-this", false, null)));
} catch (KeeperException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
zk.register(new WatcherImpl());
try {
zk.getData("/zk-demo/watch-this", true, null);
} catch (KeeperException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws IOException, KeeperException, InterruptedException {
ZoomkeepTest2 zt = new ZoomkeepTest2();
}
}
2 Run “zkCli.cmd” and set node date:
set /zk-demo/watch-this data3333\\dsafsa
set /zk-demo/watch-this data3333\\dsafsa12
3 The Console will output:
已经触发了NodeDataChanged事件!
data3333\\dsafsa
已经触发了NodeDataChanged事件!
data3333\\dsafsa12
pom.xml: