在前几篇中,我们讲解了如何使用 Java ZooKeeper 库来操作ZooKeeper,但是 Java ZooKeeper 库只实现了ZooKeeper的一些基本操作,其余分布式锁,群首选举等等,都没有给出解决方法,那么有没有这么一个库来实现这些方案呢???答案是肯定的,就是我们今天要讲的Curator。
一、引入Curator:
curator有很多模块,核心的模块为
curator-framework
跟Spring-framowork-core类似,其它的模块有curator-client、curator-async等等,而我们只需要引入一个
curator-recipes
模块即可,curator-recipes 里面包含了其它模块。
因为我们的zooKeeper是 3.4.13 版本,所以 curator-recipes 也要使用 2.x.x 版本,如果使用更高版本会出现
org.apache.zookeeper.KeeperException$UnimplementedException: KeeperErrorCode = Unimplemented for...
错误
所以我的引入为:
<!-- curator -->
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-recipes</artifactId>
<version>2.12.0</version>
</dependency>
二、Curator中的增删查改与时间监听:
ZooKeeper中的增删查改,分别对应create、delete、(get,ls2,state)、set命令,那么用Curator实现的代码为:
1、连接ZooKeeper:
// 重试策略
RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
CuratorFramework client = CuratorFrameworkFactory.newClient(env.getProperty("zookeeper.url"), retryPolicy);
client.start();
2、create:
// 增加,对应命令 create
client.create().withMode(CreateMode.PERSISTENT).forPath(curatorPath, "curator_data".getBytes());
3、delete:
// 删
client.delete().forPath(curatorPath + "/" + childList.get(0));
List<String> childAfterList = client.getChildren().forPath(curatorPath);
System.out.println(JSON.toJSONString("after : " + childAfterList));
4、get与stat以及其时间监听:
// 监听
client.getData().usingWatcher((CuratorWatcher) e->{
if (e.getType() == Watcher.Event.EventType.NodeDataChanged) {
System.out.println("监听数据更新 节点数据更新");
} else if (e.getType() == Watcher.Event.EventType.NodeDeleted) {
System.out.println("监听数据更新 节点被删除");
}
}).forPath(curatorPath);
client.getChildren().usingWatcher((CuratorWatcher) e->{
if (e.getType() == Watcher.Event.EventType.NodeChildrenChanged) {
System.out.println("监听子节点更新 节点数据更新");
}
}).forPath(curatorPath);