千家信息网

Curator教程(一)watcher监听

发表于:2025-01-31 作者:千家信息网编辑
千家信息网最后更新 2025年01月31日,1.watcher方式一(监听当前节点发生变更) String address = "mini1:2181,mini2:2181,mini3:2181";
千家信息网最后更新 2025年01月31日Curator教程(一)watcher监听

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);



0