Zookeeper示例之节点事件监听

上一篇 << 下一篇 >>>Zookeeper示例之集群请求


监听工作原理:
Zookeeper的Watcher机制主要包括客户端线程、服务端WatcherManager、Zookeeper服务器三部分,客户端在向Zookeeper服务器注册的同时,会将Watcher对象存储在客户端的WatcherManager当中,当Zookeeper服务器触发Watcher事件后,会向客户端发送通知(WatchedEvent),客户端线程从WatcherManager中取出对应的Watcher对象来执行回调逻辑。

/**子节点有变动监听*/
zkClient.subscribeChildChanges(path, new IZkChildListener() {
    @Override
    public void handleChildChange(String s, List list) throws Exception {
        System.out.println("s:"+s);
        System.out.println("子节点变动:");
        list.forEach(System.out::println);
    }
});
/**变动或删除监听*/
zkClient.subscribeDataChanges(path, new IZkDataListener() {
    @Override
    public void handleDataChange(String s, Object o) throws Exception {
        System.out.println("s:"+s+"\t o:"+o);
    }
    @Override
    public void handleDataDeleted(String s) throws Exception {
        System.out.println("s:"+s+"节点被删除");
    }
});
/**状态监听*/
zkClient.subscribeStateChanges(new IZkStateListener() {
    @Override
    public void handleStateChanged(Watcher.Event.KeeperState keeperState) throws Exception {

    }

    @Override
    public void handleNewSession() throws Exception {

    }

    @Override
    public void handleSessionEstablishmentError(Throwable throwable) throws Exception {

    }
});

推荐阅读:
<< << << << <<<为什么Zookeeper集群节点一定要是奇数
<< << << << << << << << << << << << <<

你可能感兴趣的:(Zookeeper示例之节点事件监听)