在创建zookeeper会话时会传入一个Watcher,里面有两个特别关键的类:KeeperState(连接状态)和EventType(事件类型)。
如何拿到事件状态
或类型
?
//获取事件的状态 Event.KeeperState state = watchedEvent.getState(); //获取事件的状态 //获取事件的类型 Event.EventType type = watchedEvent.getType(); //获取事件的类型
KeeperState表示的是客户端与服务端连接的状态。
连接状态 | 描述 |
---|---|
Disconnected | 客户端与服务器断开连接 |
SyncConnected | 客户端与服务器建立连接 |
AuthFailed | 客户端进行连接认证失败 |
ConnectedReadOnly | 客户端连接到的zookeeper服务是只读的 |
SaslAuthenticated | 用于通知客户端它们是SASL认证的 |
Expired | 客户端心跳检测没有收到服务端的响应时即认定断开连接,session失效 |
EventType表示的是节点发生变化时所触发的事件类型。
事件类型 | 描述 |
---|---|
NodeCreated | 被监听的节点被创建 |
NodeChildrenChanged | 被监听的节点的直接子节点被创建、被删除、子节点数据发生变更 |
NodeDataChanged | 被监听的节点的数据发生变更 |
NodeDeleted | 被监听的节点被删除 |
None 客户端的连接状态(KeeperState) | 发生变更 |
拿取事件状态demo
Event.KeeperState state = watchedEvent.getState(); //获取事件的状态 Event.EventType type = watchedEvent.getType(); //获取事件的类型 if (Event.KeeperState.SyncConnected.equals(state)) { switch (type) { case None: log.info("zookeeper connected success"); countDownLatch.countDown(); break; case NodeCreated: log.info("[{}] create node: {}", name, watchedEvent.getPath()); break; case NodeDeleted: log.info("[{}] delete node: {}", name, watchedEvent.getPath()); break; case NodeDataChanged: log.info("[{}] node data change: {}", name, watchedEvent.getPath()); break; case NodeChildrenChanged: log.info("[{}] node children change: {}", name, watchedEvent.getPath()); break; } }
boolean watch
List<String> getChildren(String path, boolean watch) byte[] getData(String path, boolean watch, Stat stat) Stat exists(String path, boolean watch)
Watcher watcher
zookeeper.exists("/p", true); // 注册默认的wachter zookeeper.exists("/p", new MyWatcher("Customer Watcher")); // 再注册一个watcher zookeeper.create("/p", null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); zookeeper.delete("/p", -1);
当一个节点注册了多个watcher,那么多个watcher的方法都会被回调。
zookeeper.create("/p", null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); zookeeper.getData("/p", true, null); // 注册默认的wachter zookeeper.exists("/p", true); // 注册两次默认的wachter zookeeper.setData("/p", "ppp".getBytes(), -1); zookeeper.delete("/p", -1);
注册方式 | NodeCreated | NodeChildrenChanged | NodeDataChanged | NodeDeleted |
---|---|---|---|---|
getChildren | Y | Y | ||
exists | Y | Y | Y | |
getData | Y | Y |
通过观察运行结果,总结如下:
zookeeper原生客户端的缺点