节点监听
一. PathChildrenCache
特点:
(1)永久监听指定节点下的节点
(2)只能监听指定节点下一级节点的变化,比如说指定节点”/example”, 在下面添加”node1”可以监听到,但是添加”node1/n1”就不能被监听到了
(3)可以监听到的事件:节点创建、节点数据的变化、节点删除等
使用方式
(1)创建curatorframework的client
(2)添加PathChildrenCache
(3)启动client 和 pathChildrenCache
(4)注册监听器
例子:
package cache;
import com.google.common.collect.Lists;
import discovery.ExampleServer;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.*;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.curator.utils.CloseableUtils;
import org.apache.curator.utils.ZKPaths;
import org.apache.zookeeper.KeeperException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.List;
/**
* An example of the PathChildrenCache. The example "harness" is a command processor
* that allows adding/updating/removed nodes in a path. A PathChildrenCache keeps a
* cache of these changes and outputs when updates occurs.
*/
public class PathCacheExample {
private static final String PATH = "/mq_monitor";
static CuratorFramework client = CuratorFrameworkFactory.newClient("192.168.27.55", new ExponentialBackoffRetry(1000, 3));
static PathChildrenCache pathChildrenCache = new PathChildrenCache(client, PATH, true);
public static void main(String[] args) throws Exception {
start();
}
public static void start() {
try {
client.start();
pathChildrenCache.start();
addPathChildListener(pathChildrenCache);
processCommands(client, pathChildrenCache);
} catch (Exception e) {
e.printStackTrace();
}
}
public void shutdown() {
CloseableUtils.closeQuietly(pathChildrenCache);
CloseableUtils.closeQuietly(client);
}
private static void addPathChildListener(PathChildrenCache cache) {
// a PathChildrenCacheListener is optional. Here, it's used just to log changes
PathChildrenCacheListener listener = new PathChildrenCacheListener() {
@Override
public void