Zookeeper循環監聽

Zookeeper循環監聽

親測 解決監聽一次的問題,直接上代碼

//這裏的監聽器會在成功連接之後 觸發一次,在觸發的時候就需要添加下一次需要監聽的監聽器,這樣就可以達到無限監聽目錄變化的效果
 zooKeeper = new ZooKeeper(ZOOKEEPER_HOST,10000,watchedEvent -> {
                List<String> children = null;
                try {
                ***這裏是關鍵,因爲我要監聽子目錄變化所以是getChildren,同理這裏也可以改爲exists,每次添加下次要監聽的監聽器,所以放在最外面第一次獲取連接成功的時候就要添加***
                    children = zooKeeper.getChildren(PATH, true);
                } catch (KeeperException | InterruptedException e) {
                    e.printStackTrace();
                }

                if(Watcher.Event.KeeperState.SyncConnected == watchedEvent.getState()){
                    if(Watcher.Event.EventType.None == watchedEvent.getType() && null == watchedEvent.getPath()){
                        connectedSemaphore.countDown();
                    }else if(Watcher.Event.EventType.NodeChildrenChanged == watchedEvent.getType()){
                        System.out.println("添加節點");
//                            chidren = zooKeeper.getChildren(PATH, false);
                        for (String child : children) {
                            System.out.println(child);
                          
                        }
                    }
                }
            });
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章