java zookeeper 监听
时间: 2023-08-23 11:37:04 浏览: 101
在Java中使用ZooKeeper监听节点变化需要使用ZooKeeper提供的Watcher接口。Watcher接口中定义了一个process()方法,当节点发生改变时,ZooKeeper会回调这个方法。
下面是一个简单的Java代码示例,用于监听ZooKeeper节点的变化:
```java
import org.apache.zookeeper.*;
import java.io.IOException;
public class ZooKeeperWatcher implements Watcher {
private ZooKeeper zooKeeper;
public ZooKeeperWatcher(String connectString, int sessionTimeout) throws IOException, KeeperException, InterruptedException {
zooKeeper = new ZooKeeper(connectString, sessionTimeout, this);
// 创建一个节点,用于后面的演示
zooKeeper.create("/test", "hello".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
public void process(WatchedEvent event) {
if (event.getType() == Event.EventType.NodeDataChanged) {
try {
byte[] data = zooKeeper.getData(event.getPath(), this, null);
System.out.println("Node data changed: " + new String(data));
} catch (KeeperException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws IOException, KeeperException, InterruptedException {
ZooKeeperWatcher watcher = new ZooKeeperWatcher("localhost:2181", 5000);
Thread.sleep(Integer.MAX_VALUE);
}
}
```
在这个代码中,我们定义了一个ZooKeeperWatcher类,其中实现了Watcher接口。在类的构造函数中,我们首先连接ZooKeeper,并创建了一个名为“/test”的节点。在process()方法中,我们判断事件类型是否为“NodeDataChanged”,如果是,我们就获取节点的最新数据,并输出到控制台。最后,我们在main()方法中启动了一个线程,以保持程序的运行。
当节点的数据发生变化时,程序将会输出一个消息,如下所示:
```
Node data changed: world
```
阅读全文