1,监听器简单代码,需要测试
package com.coder.flink.core.a_zk; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.recipes.cache.ChildData; import org.apache.curator.framework.recipes.cache.NodeCache; import org.apache.curator.framework.recipes.cache.NodeCacheListener; import org.apache.curator.retry.ExponentialBackoffRetry; import org.apache.curator.utils.EnsurePath; import java.util.concurrent.CountDownLatch; public class NodeCacheExample { private static final String PATH = "/tmp2"; private static CountDownLatch latch = new CountDownLatch(1); static NodeCache nodeCache; static CuratorFramework client; static { client = CuratorFrameworkFactory.newClient( "node1:2181", 5000, 5000, new ExponentialBackoffRetry( 1000, 3)); client.start(); } public static void initCache() throws Exception { // client.create().forPath(PATH); // client.setData().forPath(PATH, "节点的初始值".getBytes()); nodeCache = new NodeCache(client, PATH); EnsurePath ensurePath = client.newNamespaceAwareEnsurePath(PATH); ensurePath.ensure(client.getZookeeperClient()); //设置成true,那么nodeCache在第一次启动的时候就会到zookeeper上去获取节点的数据内容,并保存在cache中 nodeCache.start(true); startCache(nodeCache); } private static void startCache(final NodeCache cache) throws Exception { ChildData data = cache.getCurrentData(); System.out.println("第一次启动获取到的内容:" + new String(data.getData())); cache.getListenable().addListener(new NodeCacheListener() { @Override public void nodeChanged() throws Exception { System.out.println("监听器获取到的数据: " + new String(cache.getCurrentData().getData())); latch.countDown(); } }); /* Thread.sleep(2000); if(client.checkExists().forPath(PATH) != null){ System.out.println("node is exist,准备给节点设置新的内容"); client.setData().forPath(PATH, "节点新内容".getBytes()); client.setData().forPath(PATH, "节点新内容2".getBytes());