一 简介
Apache Curator 是一个比较完善的 ZooKeeper 客户端框架,通过封装的一套高级 API 简化了 ZooKeeper 的操作。通过查看官方文档,可以发现 Curator 主要解决了三类问题:
- 封装 ZooKeeper client 与 ZooKeeper server 之间的连接处理
- 提供了一套 Fluent 风格的操作 API
- 提供 ZooKeeper 各种应用场景 (recipe,比如:分布式锁服务、集群领导选举、共享计数器、缓存机制、分布式队列等) 的抽象封装
Curator 主要从以下几个方面降低了 zk 使用的复杂性:
- 重试机制:提供可插拔的重试机制,它将给捕获所有可恢复的异常配置一个重试策略,并且内部也提供了几种标准的重试策略 (比如指数补偿)
- 连接状态监控:Curator 初始化之后会一直对 zk 连接进行监听,一旦发现连接状态发生变化将会作出相应的处理
- zk 客户端实例管理:Curator 会对 zk 客户端到 server 集群的连接进行管理,并在需要的时候重建 zk 实例,保证与 zk 集群连接的可靠性
- 各种使用场景支持:Curator 实现了 zk 支持的大部分使用场景 (甚至包括 zk 自身不支持的场景),这些实现都遵循了 zk 的最佳实践,并考虑了各种极端情况
二 基于 Curator 的 ZooKeeper 基本用法
public class CuratorBase {
//会话超时时间
private final int SESSION_TIMEOUT = 30 * 1000;
//连接超时时间
private final int CONNECTION_TIMEOUT = 3 * 1000;
//ZooKeeper 服务地址
private static final String CONNECT_ADDR = "192.168.1.1:2100,192.168.1.1:2101,192.168.1.3:2102";
//创建连接实例
private CuratorFramework client = null;
public static Exception {
(, );
CuratorFrameworkFactory.builder()
.connectString(CONNECT_ADDR).connectionTimeoutMs(CONNECTION_TIMEOUT)
.sessionTimeoutMs(SESSION_TIMEOUT)
.retryPolicy(retryPolicy)
.build();
client.start();
System.out.println(States.CONNECTED);
System.out.println(client.getState());
client.create().forPath(,.getBytes());
client.create().withMode(CreateMode.PERSISTENT_SEQUENTIAL).forPath(,.getBytes());
client.create().withMode(CreateMode.EPHEMERAL)
.forPath(,.getBytes());
client.create().withMode(CreateMode.EPHEMERAL_SEQUENTIAL).forPath(,.getBytes());
client.create().withProtection().withMode(CreateMode.EPHEMERAL_SEQUENTIAL).forPath(,.getBytes());
client.checkExists().forPath();
client.checkExists().forPath();
System.out.println( + (stat1 != ? : ));
System.out.println( + (stat2 != ? : ));
System.out.println(client.getChildren().forPath());
System.out.println( (client.getData().forPath()));
client.setData().forPath(,.getBytes());
client.create().orSetData().creatingParentContainersIfNeeded()
.forPath(,.getBytes());
client.create().orSetData().creatingParentContainersIfNeeded()
.forPath(,.getBytes());
client.create().forPath(,.getBytes());
client.delete().forPath();
client.delete().guaranteed().deletingChildrenIfNeeded().forPath();
}
}

