The principle and ZK Watcher

What is ZK Watcher

Based on a common demand for ZK applications is the need to know the state of ZK collection. For this purpose, a method is polling ZK ZK client set the timing to check if the system status has changed. However, polling is not an efficient way, particularly in the frequency state change when the low

Thus, ZK provided a poll to avoid performance problems caused by a particular time of interest notification client mode, i.e. provided Watcher manner. By setting Watcher, ZK client can request a notification to the specified znode registration, receive notification when a single znode changes. For example, the deleted Watcher sending node to be deleted when znode notice

ZK Watcher application code typically follows the following framework

zk.exists("myZnode", myWatcher, existsCallback, null);

Watcher myWatcher new Watcher() {
  public void process(WatchedEvent event) {
    // process the watch event
  }
}

StatCallback existsCallback = new StatCallback() {
  public void processResult(int rc, String path, Object ctx, Stat stat) {
    // process the result of the exists call
  }
}

The above code framework exists to operate, for example, it shows the general use of asynchronous call ZK and register the Watcher

Classification of WatchedEvent

Watcher use an important element is to understand how and when to set Watcher trigger, not all operations can be set ZK Watcher, Watcher is not all events will be triggered

Despite the connection status of being overloaded WatchedEvent, WatchedEvent course of business will be divided into the following encounter

  • NodeCreated - can be set by calling exists Watcher, is triggered when znode created from scratch
  • NodeDeleted - Watcher can be set by calling getData exists or is triggered when znode be deleted
  • NodeDataChanged - Watcher can be set by calling getData exists or is triggered when data changes in znode
  • NodeChildrenChanged - trigger can be called to set Watcher by getChildren, created or deleted in direct child of znode
  • DataWatchRemoved - trigger corresponding Watcher Watcher exists or when getData set are deleted
  • ChildWatchRemoved - Watcher in the corresponding trigger setting is deleted Watcher getChildren

We can see that only exists and getData and getChildren three operations to set Watcher

Note, Watcher getData created not receive NodeCreated event, because when getData node does not exist KeeperException.NoNodeException will throw an exception, but does not set the Watcher.

 

Guess you like

Origin www.cnblogs.com/jvStarBlog/p/11567077.html