1. 程式人生 > >Curator之PathChildrenCache子節點監聽

Curator之PathChildrenCache子節點監聽

Curator之PathChildrenCache子節點監聽:

/*子節點監聽*/
        //子節點新增watcher
        //PathChildrenCache:監聽資料節點的增刪改,會觸發事件
        String childNodePathCache = nodePath;
        //childData:設定快取節點的資料狀態
        final PathChildrenCache childrenCache = new PathChildrenCache(cto.client,childNodePathCache,true);

        /*
        * StartMode:初始化方式
        * POST_INITIALIZED_EVENT:非同步初始化。初始化後會觸發事件
        * NORMAL:非同步初始化
        * BUILD_INITIAL_CACHE:同步初始化
        * */
        childrenCache.start(PathChildrenCache.StartMode.POST_INITIALIZED_EVENT);

        List<ChildData> childDataList = childrenCache.getCurrentData();
        System.out.println("當前資料節點的子節點資料列表:");
        for(ChildData cd : childDataList){
            String childData = new String(cd.getData());
            System.out.println(childData);
        }

        childrenCache.getListenable().addListener(new PathChildrenCacheListener() {
            public void childEvent(CuratorFramework ient, PathChildrenCacheEvent event) throws Exception {
               if(event.getType().equals(PathChildrenCacheEvent.Type.INITIALIZED)){
                   System.out.println("子節點初始化成功");
               }else if(event.getType().equals(PathChildrenCacheEvent.Type.CHILD_ADDED)){
                   System.out.println("新增子節點路徑:"+event.getData().getPath());
                   System.out.println("子節點資料:"+new String(event.getData().getData()));
               }else if(event.getType().equals(PathChildrenCacheEvent.Type.CHILD_REMOVED)){
                   System.out.println("刪除子節點:"+event.getData().getPath());
               }else if(event.getType().equals(PathChildrenCacheEvent.Type.CHILD_UPDATED)){
                   System.out.println("修改子節點路徑:"+event.getData().getPath());
                   System.out.println("修改子節點資料:"+new String(event.getData().getData()));
               }
            }
        });

在這裡插入圖片描述在這裡插入圖片描述