watcher机制
- 针对每个节点的操作,都会有一个监督者->watcher
- 当监控的某个对象(znode)发生了变化,则触发watcher事件
- zk中的watcher是一次性的,触发后立即销毁
- 父节点、子节点增删改都能够触发其watcher
- 针对不同类型的操作,则触发的watcher事件也不同
- (子)节点创建事件
- (子)节点删除事件
- (子)节点数据变化事件
watcher常用命令使用
创建父节点触发: NodeCreated
为/lzc创建一个watcher事件,当/lzc被创建时就会触发
[zk: localhost:2181(CONNECTED) 6] stat /lzc watcher
Node does not exist: /lzc
忽略此时的错误,因为此时/lzc确实不存在,但是watcher还是会被设置
接下来创建/lzc
[zk: localhost:2181(CONNECTED) 7] create /lzc lzc-data
WATCHER::
WatchedEvent state:SyncConnected type:NodeCreated path:/lzc
Created /lzc
我们可以看到WATCHER事件已经触发,触发事件类型为NodeCreated,针对的路径为/lzc
修改父节点触发: NodeDataChanged
前面已经使用了stat来设置watcher事件,这次使用get来设置watcher事件。
[zk: localhost:2181(CONNECTED) 17] get /lzc watcher
lzc-data
cZxid = 0x1a
ctime = Sat Mar 16 23:17:20 CST 2019
mZxid = 0x1e
mtime = Sat Mar 16 23:24:02 CST 2019
pZxid = 0x1a
cversion = 0
dataVersion = 4
aclVersion = 0
ephemeralOwner = 0x0
dataLength = 8
numChildren = 0
重新为/lzc设置数据
[zk: localhost:2181(CONNECTED) 18] set /lzc new-lzc-data
WATCHER::
WatchedEvent state:SyncConnected type:NodeDataChanged path:/lzc
cZxid = 0x1a
ctime = Sat Mar 16 23:17:20 CST 2019
mZxid = 0x1f
mtime = Sat Mar 16 23:24:54 CST 2019
pZxid = 0x1a
cversion = 0
dataVersion = 5
aclVersion = 0
ephemeralOwner = 0x0
dataLength = 12
numChildren = 0
我们可以看到WATCHER事件已经触发,触发事件类型为NodeDataChanged,针对的路径为/lzc
删除父节点触发: NodeDeleted
由于watcher事件是一次性的,因此我们需要重新为/lzc设置watcher事件
[zk: localhost:2181(CONNECTED) 24] get /lzc watcher
new-lzc-data
cZxid = 0x21
ctime = Sat Mar 16 23:29:53 CST 2019
mZxid = 0x21
mtime = Sat Mar 16 23:29:53 CST 2019
pZxid = 0x21
cversion = 0
dataVersion = 0
aclVersion = 0
ephemeralOwner = 0x0
dataLength = 12
执行删除/lzc操作
[zk: localhost:2181(CONNECTED) 25] delete /lzc
WATCHER::
WatchedEvent state:SyncConnected type:NodeDeleted path:/lzc
我们可以看到WATCHER事件已经触发,触发事件类型为NodeDeleted,针对的路径为/lzc
ls为父节点设置watcher,创建子节点触发: NodeChildrenChanged
查看当前节点
[zk: localhost:2181(CONNECTED) 28] ls /
[zookeeper, lzc]
使用ls对/lzc设置watcher事件
[zk: localhost:2181(CONNECTED) 30] ls /lzc watcher
[]
为/lzc创建一个子节点
[zk: localhost:2181(CONNECTED) 32] create /lzc/abc abc-data
WATCHER::
WatchedEvent state:SyncConnected type:NodeChildrenChanged path:/lzc
Created /lzc/abc
我们可以看到触发事件为NodeChildrenChanged
ls为父节点设置watcher,删除子节点触发: NodeChildrenChanged
[zk: localhost:2181(CONNECTED) 38] ls /lzc/abc watcher
[]
[zk: localhost:2181(CONNECTED) 39] delete /lzc/abc
WATCHER::
WatchedEvent state:SyncConnected type:NodeDeleted path:/lzc/abc
我们可以看到触发事件为NodeDeleted
ls为父节点设置watcher,修改子节点不触发事件
[zk: localhost:2181(CONNECTED) 51] ls /
[zookeeper, lzc]
[zk: localhost:2181(CONNECTED) 52] ls /lzc
[abc]
[zk: localhost:2181(CONNECTED) 53] ls /lzc watcher
[abc]
[zk: localhost:2181(CONNECTED) 54] set /lzc/abc aabbaabb
cZxid = 0x29
ctime = Sat Mar 16 23:41:36 CST 2019
mZxid = 0x2b
mtime = Sat Mar 16 23:45:37 CST 2019
pZxid = 0x29
cversion = 0
dataVersion = 2
aclVersion = 0
ephemeralOwner = 0x0
dataLength = 8
numChildren = 0