引入依赖
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-recipes</artifactId>
<version>2.7.1</version>
</dependency>
连接
String ADDRESS = "192.168.1.200:2181";
CuratorFramework client = CuratorFrameworkFactory.newClient(ADDRESS, new RetryNTimes(10, 5000));
client.start();
基本命令
curator使用Builder模式,先获取对应ls getData getChildren create delete等命令对应的Builder接口,然后在调用forPath指定位置,或者设置监听。
// 获取一个节点的内容
byte[] d = client.getData().forPath("/lw/1");
System.out.println(new String(d));
监听
curator的监听有三种:
1.NodeCache 监听一个节点,子节点也不关心
NodeCache cache = new NodeCache(client, "/lw/12");
cache.getListenable().addListener(() -> {
System.out.println("--------------");
});
cache.start();
2.PathChildrenCache 监听一个节点和其子节点,孙子节点不监听
PathChildrenCache pathChildrenCache = new PathChildrenCache(client, "/lw", true);
pathChildrenCache.getListenable().addListener(new PathChildrenCacheListener() {
@Override
public void childEvent(CuratorFramework curatorFramework, PathChildrenCacheEvent event) throws Exception {
System.out.println(event.getType().name());
}
});
pathChildrenCache.start(PathChildrenCache.StartMode.BUILD_INITIAL_CACHE);
3.TreeCache 监听所以子孙节点
TreeCache tree = new TreeCache(client, "/lw");
tree.getListenable().addListener((c, event) -> {
System.out.println(event.getType().name());
});
tree.start();