NOTE

ZooKeeper Watches

What ZooKeeper's event-watching mechanism is, how to use it, one-shot watch behavior, and how the watcher mechanism works.

ZooKeeperCreated Updated 2 min readhistorical

This is a historical learning note and may contain outdated or incomplete understanding.

1. What Is the Event-Watching Mechanism

ZooKeeper allows a client to register a Watcher on a Znode on the server. When certain specified events on the server trigger this Watcher, the server sends an event notification to the specified client to implement distributed notification. The client then makes business changes according to the Watcher notification state and event type.

After a watch is set, ZooKeeper notifies the client when the node’s data or structure changes. ZooKeeper currently has the following four event types:

  • Node creation
  • Node deletion
  • Node data change
  • Child-node change

2. Using the Event-Watching Mechanism

  • Watch child-node changes
# Client 1 watches child-node changes
ls -w /zk_test

# Client 2 creates a child node
create /zk_test/test-4

# Client 1 triggers the watch event
WATCHER::

WatchedEvent state:SyncConnected type:NodeChildrenChanged path:/zk_test
  • Watch node-data changes
# Client 1 watches node-data changes
get -w /zk_test

# Client 2 modifies node data
set /zk_test oopp

# Client 1 triggers the watch event
WATCHER::

WatchedEvent state:SyncConnected type:NodeDataChanged path:/zk_test

3. Notes on the Event-Watching Mechanism

3.1. Are Watch Notifications on a Node Permanent?

No. A Watch event is a one-time trigger. When the watched node changes, the server pushes this change to the client, but it does not also push the changed data, so the client needs to query again to obtain the data.

3.1.1. Why Is It Not Permanent?

For example, if the server changes frequently and there are many listening clients, every change would have to be sent to all clients, placing heavy pressure on the network and server.

4. Principle of the Event-Watching Mechanism

ZooKeeper Watcher Principle

  • Create the ZooKeeper client in the main thread; at the same time create two threads, where connect is responsible for network connection communication and listener is responsible for watching.
  • The connect thread sends the registered watch event to ZooKeeper.
  • ZooKeeper adds the watch event to the watcher list.
  • When ZooKeeper detects a data or path change, it sends this message to the listener thread.
  • The listener thread internally calls the process() method.

5. References

Discussion

Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub