Moving to @users...

There's not enough of a code snippet to answer properly. However, I'd use a 
LeaderSelector instead and allocate/use the PathChildrenCache inside of it. 

-Jordan

> On Dec 21, 2017, at 5:12 AM, 習慣/zt①个 <381954...@qq.com> wrote:
> 
> Hello:
>        I'd like to launch a APP which replicas is 2. These two same APPs used 
> 'PathChildrenCache' to watch a ZK path. 
> I expect that the only one app(the leader) execute the 
> 'PathChildrenCacheListener' event. Do i need to wait the leader elect 
> completely 
> before executing 'PathChildrenCacheListener' event ?
>        I worry that node changing trigger 'PathChildrenCacheListener' event 
> before electing leader completely, especially in unstable network.
> 
> [demo]:
> PathChildrenCache cache = new PathChildrenCache(client, nodePath, false);
> cache.getListenable().addListener(new PathChildrenCacheListener() {
>    @Override
>    public void childEvent(CuratorFramework client, PathChildrenCacheEvent 
> event) throws Exception {
>       if (event.getType() == Type.CHILD_ADDED
>             || event.getType() == Type.CHILD_REMOVED) {
>          
>          // wait leader elect completely
>          while (!leaderLatch.getLeader().isLeader()) {
>             try {
>                TimeUnit.MILLISECONDS.sleep(1000);
>             } catch (InterruptedException e) {
>                Thread.currentThread().interrupt();
>             }
>          }
>          
>          String node = ZKPaths.getNodeFromPath(event.getData().getPath());
>          if (leaderLatch.hasLeadership()) {
>             switch (event.getType()) {
>                case CHILD_ADDED:
>                   log.info("Added node : {}", node);
>                   // TODO: 2017/12/21
>                   break;
>                case CHILD_REMOVED:
>                   log.info("Removed node : {}", node);
>                   // TODO: 2017/12/21
>                   break;
>             }
>          } else {
>             log.info("This LeaderLatch is not leader");
>          }
>       }
>    }
> });
> cache.start();
> 

Reply via email to