ZooKeeper客户端可以对指定节点设置指定Watcher,当服务器指定节点发生变化是,客户端会收到服务器的通知,然后客户端可以执行相应Watcher的代码。

  默认ZooKeeper内置了一个watcher,用于打印收到的服务器的通知。

源码ZooKeeperMain.Watcher:

 1 protected void connectToZK(String newHost) throws InterruptedException, IOException {
 2         if (zk != null && zk.getState().isAlive()) {
 3             zk.close();
 4         }
 5         host = newHost;
 6         zk = new ZooKeeper(host,
 7                  Integer.parseInt(cl.getOption("timeout")),
 8                  new MyWatcher());
 9  }
10 
11 private class MyWatcher implements Watcher {
12         public void process(WatchedEvent event) {
13             if (getPrintWatches()) {
14                 ZooKeeperMain.printMessage("WATCHER::");
15                 ZooKeeperMain.printMessage(event.toString());
16             }
17         }
18  }
View Code

相关文章: