三个监听器zookeeper的API:NodeCache TreeCache PathChildrenCache
1.NodeChache
private CuratorFramework client; @Before public void buildsCurator() { RetryPolicy re = new ExponentialBackoffRetry(3000,10,5000);//int baseSleepTimeMs, int maxRetries, int maxSleepMs client = CuratorFrameworkFactory.builder().connectString("192.168.214.33:2181").sessionTimeoutMs(60000) .connectionTimeoutMs(1500).retryPolicy(re).namespace("com").build(); client.start(); } @After public void close() { if (client != null) client.close(); }
//NodeCache @Test public void testNodeCache() throws Exception { // 1.创建NodeCache对象 final NodeCache nc = new NodeCache(client,"/it01"); //CuratorFramework client, String path // 2.注册监听 nc.getListenable().addListener(new NodeCacheListener() { public void nodeChanged() throws Exception { System.out.println("单个节点被修改了.........."); byte[] data = nc.getCurrentData().getData(); System.out.println(new String(data)); } }); // 3.启动监听 nc.start(true); // 4.while true while (true) { } }
2.PathChildrenCache
//PathChildrenCache @Test public void pathChildrenCache() throws Exception { //1.创建PathChildrenCache对象 final PathChildrenCache pcc = new PathChildrenCache(client,"/it01",true); //2.获取监听器 pcc.getListenable().addListener(new PathChildrenCacheListener() { public void childEvent(CuratorFramework curatorFramework, PathChildrenCacheEvent pathChildrenCacheEvent) throws Exception { System.out.println("节点变化了...."); System.out.println(pathChildrenCacheEvent); PathChildrenCacheEvent.Type type = pathChildrenCacheEvent.getType(); //update if (type.equals(PathChildrenCacheEvent.Type.CHILD_UPDATED)) { System.out.println("修改数据为====>" + new String(pathChildrenCacheEvent.getData().getData())); } } }); //3.启动监听器 pcc.start(); while (true) {} }
3.TreeCache
@Test public void treeCache() throws Exception { TreeCache tc = new TreeCache(client,"/"); tc.getListenable().addListener(new TreeCacheListener() { public void childEvent(CuratorFramework curatorFramework, TreeCacheEvent treeCacheEvent) throws Exception { System.out.println("==============>节点变化了"); System.out.println(treeCacheEvent); TreeCacheEvent.Type type = treeCacheEvent.getType(); if (type.equals(TreeCacheEvent.Type.NODE_UPDATED)) { System.out.println("================>" + new String(treeCacheEvent.getData().getData())); } } }); tc.start(); while (true){} }