1.watcher方式一(监听当前节点发生变更)
String address = "mini1:2181,mini2:2181,mini3:2181"; RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 10); CuratorFramework client = CuratorFrameworkFactory.newClient(address, new ExponentialBackoffRetry(1000, 3)); client.start(); //创建节点watcher监听 final NodeCache cache = new NodeCache(client, "/super", false); cache.start(true); cache.getListenable().addListener(new NodeCacheListener() { public void nodeChanged() throws Exception { System.out.println(cache.getCurrentData().getPath()); System.out.println(cache.getCurrentData().getStat()); } });
2.watcher方式二(监听当前节点的子节点发生变更)
String address = "mini1:2181,mini2:2181,mini3:2181"; RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 10); CuratorFramework client = CuratorFrameworkFactory.newClient(address, new ExponentialBackoffRetry(1000, 3)); client.start(); //创建子节点watcher监听 PathChildrenCache cache = new PathChildrenCache(client, "/super", true); cache.start(StartMode.POST_INITIALIZED_EVENT); cache.getListenable().addListener(new PathChildrenCacheListener() { public void childEvent(CuratorFramework cf, PathChildrenCacheEvent event) throws Exception { System.out.println(event.getType()); } }); Thread.sleep(Long.MAX_VALUE);
原创文章,作者:Maggie-Hunter,如若转载,请注明出处:https://blog.ytso.com/tech/opensource/192207.html