Zookeeper客户端 原生API、ZKClient和Curator简单介绍: https://blog.csdn.net/xiaojin21cen/article/details/88537916
官网:http://curator.apache.org/index.html
Apache Curator是Apache ZooKeeper的Java / JVM客户端库,Apache ZooKeeper是一种分布式协调服务。它包括一个高级API框架和实用程序,使Apache ZooKeeper更容易和更可靠。它还包括常见用例和扩展(如服务发现和Java 8异步DSL)的配方。
组名名称 | 用途 |
---|---|
Client | Zookeeper 客户端的封装,用于取代原生的 Zookeeper 客户端, 提供了一些底层处理和相关的工具方法。 |
Framework | 简化 Zookeeper 高级功能的使用,并增加了一些新的功能,比如 Zookeeper 集群连接、重试等。 |
Recipes | Zookeeper 所有的典型应用场景的实现(除了两阶段提交外) ,该组件依赖 Client 和 Framework 。 包括 监听、各种分布式锁(可重入锁、排他锁、共享锁、信号锁等)、缓存、队列、选举、分布式 atomic(分布式计数器)、分布式Barrier 等等。 |
Utilities | 为 Zookeeper 提供的各种工具类。 |
Errors | Curator 异常处理, 连接, 恢复等。 |
(地址:https://search.maven.org/search?q=org.apache.curator)
GroupID/Org | ArtifactID/Name | 描述 |
---|---|---|
org.apache.curator | curator-recipes | 所有典型应用场景。需要依赖client和framework,需设置自动获取依赖。 |
org.apache.curator | curator-framework | 同组件中framework介绍。 |
org.apache.curator | curator-client | 同组件中client介绍。 |
org.apache.curator | curator-test | 包含TestingServer、TestingCluster和一些测试工具。 |
org.apache.curator | curator-examples | 各种使用Curator特性的案例。 |
org.apache.curator | curator-x-discovery | 在framework上构建的服务发现实现。 |
org.apache.curator | curator-x-discoveryserver | 可以和Curator Discovery一起使用的RESTful服务器。 |
org.apache.curator | curator-x-rpc | Curator framework和recipes非java环境的桥接。 |
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-recipes</artifactId>
<version>4.1.0</version>
</dependency>
public class Test{
public static void main(String[] args) {
String zkConnectionString = "localhost:2181";
RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
CuratorFramework client = CuratorFrameworkFactory.newClient(zkConnectionString, retryPolicy);
client.start();
try {
//创建分布式锁, 锁空间的根节点路径为 /curator/lock
InterProcessMutex lock = new InterProcessMutex(client, "/curator/lock");
if ( lock.acquire(1000, TimeUnit.SECONDS) ) {
// do some work inside of the critical section here
System.out.println("do some work inside of the critical section here");
}
} catch (Exception e) {
e.printStackTrace();
}finally{
//完成业务流程, 释放锁
lock.release();
}
}
}
转载: https://blog.csdn.net/belvine/article/details/87610059