在 ZooKeeper 中,客户端可以注册 Watcher 来监听节点的变化,并在节点发生变化时得到通知。以下是一个简单的 Java 示例,展示了如何在 ZooKeeper 客户端注册 Watcher。
import org.apache.zookeeper.*;
import java.io.IOException;
public class ZookeeperWatcherExample implements Watcher {
private static final String ZOOKEEPER_ADDRESS = "127.0.0.1:2181"; // ZooKeeper服务器地址
private static final int SESSION_TIMEOUT = 3000; // 会话超时时间
private static ZooKeeper zooKeeper;
public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
ZookeeperWatcherExample example = new ZookeeperWatcherExample();
example.connectToZookeeper();
// 创建节点,并注册 Watcher 监听节点变化
String path = "/examplePath";
zooKeeper.create(path, "InitialData".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
// 注册 Watcher
zooKeeper.exists(path, example);
// 为了能够看到 Watcher 的效果,这里进行阻塞
Thread.sleep(Long.MAX_VALUE);
}
private void connectToZookeeper() throws IOException {
zooKeeper = new ZooKeeper(ZOOKEEPER_ADDRESS, SESSION_TIMEOUT, this);
}
@Override
public void process(WatchedEvent event) {
// Watcher 事件回调方法
if (event.getType() == Event.EventType.NodeCreated) {
System.out.println("Node created: " + event.getPath());
} else if (event.getType() == Event.EventType.NodeDeleted) {
System.out.println("Node deleted: " + event.getPath());
} else if (event.getType() == Event.EventType.NodeDataChanged) {
System.out.println("Node data changed: " + event.getPath());
} else if (event.getType() == Event.EventType.NodeChildrenChanged) {
System.out.println("Node children changed: " + event.getPath());
}
try {
// 重新注册 Watcher
zooKeeper.exists(event.getPath(), this);
} catch (Exception e) {
e.printStackTrace();
}
}
}
在这个示例中,ZookeeperWatcherExample
类实现了 Watcher
接口,并重写了其中的 process
方法。在 main
方法中,连接到 ZooKeeper 服务器后,创建了一个节点,并注册了 Watcher 监听该节点的变化。
Watcher 回调方法中根据事件类型进行相应的处理,并重新注册 Watcher 以监听下一次的节点变化。这个示例中的 Watcher 是针对节点的变化,可以根据需要注册不同类型的 Watcher,监听不同的事件。