Zookeeper监听器原理

1、监听器详情

Zookeeper监听器原理_第1张图片
1)首先要有一个main()线程
2)在main线程中创建Zookeeper客户端,这时就会创建两个线程,一个负责网络连接通信(connet),一个负责监听(listener)。
3)通过connect线程将注册的监听事件发送给Zookeeper。
4)在Zookeeper的注册监听器列表中将注册的监听事件添加到列表中。
5)Zookeeper监听到有数据或路径变化,就会将这个消息发送给listener线程。
6)listener线程内部调用了process()方法。

2、常见的监听

1)监听节点数据的变化

get path [watch]

2)监听子节点增减的变化

ls path [watch]

3、实例

节点的值变化监听
(1)在 hadoop104 主机上注册监听/sanguo 节点数据变化

[zk: localhost:2181(CONNECTED) 0] get /sanguo watch

xisi
cZxid = 0x200000002
ctime = Wed Aug 18 23:07:18 CST 2021
mZxid = 0x300000007
mtime = Thu Aug 19 11:53:03 CST 2021
pZxid = 0x200000012
cversion = 8
dataVersion = 3
aclVersion = 0
ephemeralOwner = 0x0
dataLength = 4
numChildren = 4

(2)在 hadoop103 主机上修改/sanguo 节点的数据

[zk: localhost:2181(CONNECTED) 1] set /sanguo "xisi"

cZxid = 0x200000002
ctime = Wed Aug 18 23:07:18 CST 2021
mZxid = 0x30000000a
mtime = Thu Aug 19 11:54:19 CST 2021
pZxid = 0x200000012
cversion = 8
dataVersion = 4
aclVersion = 0
ephemeralOwner = 0x0
dataLength = 4
numChildren = 4

(3)观察 hadoop104 主机收到数据变化的监听

[zk: localhost:2181(CONNECTED) 1] 
WATCHER::

WatchedEvent state:SyncConnected type:NodeDataChanged path:/sanguo

注意:在hadoop103再多次修改/sanguo的值,hadoop104上不会再收到监听。因为注册一次,只能监听一次。想再次监听,需要再次注册。

节点的子节点变化监听(路径变化)
(1)在 hadoop104 主机上注册监听/sanguo 节点的子节点变化

[zk: localhost:2181(CONNECTED) 1] ls /sanguo watch

[weiguo0000000003, weiguo0000000002, weiguo0000000004, shuguo]

(2)在 hadoop103 主机/sanguo 节点上创建子节点

[zk: localhost:2181(CONNECTED) 2] create /sanguo/jin "simayi"

Created /sanguo/jin

(3)观察 hadoop104 主机收到子节点变化的监听

[zk: localhost:2181(CONNECTED) 2] 
WATCHER::

WatchedEvent state:SyncConnected type:NodeChildrenChanged path:/sanguo

注意:节点的路径变化,也是注册一次,生效一次。想多次生效,就需要多次注册。

你可能感兴趣的:(Zookeeper,zookeeper)