[zookeeper]3.zookeeper监听


Zookeeper has two types of monitoring

  • Monitor changes in the node directory (add and delete nodes)

    ls -w /path

Create a permanent node of /sanguo/shuguo (note: temporary nodes are not allowed to have children)

[zk: localhost:2181(CONNECTED) 5] create -s /sanguo/shuguo  joke
Created /sanguo/shuguo0000000005

zkClient listens to changes in the /sanguo directory

[zk: localhost:2181(CONNECTED) 4] ls -w /sanguo
[shuguo, shuguo0000000002, shuguo0000000003, shuguo0000000004]
[zk: localhost:2181(CONNECTED) 5]
WATCHER::

WatchedEvent state:SyncConnected type:NodeChildrenChanged path:/sanguo

  • Monitor changes in node data (modify the value of the node)

    get -w /path

The client modifies the value of /sanguo

[zk: localhost:2181(CONNECTED) 0] get /sanguo
古代中国
[zk: localhost:2181(CONNECTED) 1] set /sanguo "古中国"

The zkClient client monitors the change of the value of /sanguo

[zk: localhost:2181(CONNECTED) 20] get -w /sanguo
古代中国
[zk: localhost:2181(CONNECTED) 21]
WATCHER::

WatchedEvent state:SyncConnected type:NodeDataChanged path:/sanguo

Note: 1. The client must first register to listen.
2. If the directory or data changes, the server informs the client. After the client receives the notification of the listening event, it will not continue to monitor.
3. Need to re-register to monitor.



Implementation of zookeeper monitoring mechanism

1. Create a zkClient client.

2. Start two threads in the main() method of zkClient.
connect thread: connect to zkServer and send monitoring requests. (Request to monitor node directory or node data).
Listen thread: used to wait for the processing of zkServer's listening notification.

3. The connect thread of zkClient connects to zkServer and sends a request for monitoring events.

4. After receiving the zkClient's monitoring request, zkServer establishes a monitoring list and registers the monitoring events in the list.

5. Once zkServer finds the occurrence of the registered monitoring event, it will immediately notify zkClient.

6. The listen thread of zkClient calls process() to process the monitoring notification.

[zookeeper]3.zookeeper监听

Guess you like

Origin blog.51cto.com/phpme/2603710