简介
curatorframework是一款开源的zookeeper客户端框架,能够非常方便的对zk进行管理。管理zk首先要与zk建立连接。
与zk建立连接的方式
官方文档上给出了两种方式与zk建立连接
- 使用工厂方法
使用builder模式
工厂方法建立zk连接实例
public static CuratorFramework createSimple(String connectionString)
{
/** 重试策略
* 第一个参数是发生第一次重试之前的等待时间
* 第二个参数是重试次数
* 重试等待时间以第一次为初始值,之后按照指数增长
* 比如例子中给出的,第一次重试的等待时间1s
* 第二次重试的等待时间是2s,第三次重试的等待时间是4s
*/
ExponentialBackoffRetry retryPolicy = new ExponentialBackoffRetry(1000, 3);
// The simplest way to get a CuratorFramework instance. This will use default values.
// The only required arguments are the connection string and the retry policy
return CuratorFrameworkFactory.newClient(connectionString, retryPolicy);
}
(2)使用builder模式创建连接
public static CuratorFramework createWithOptions(String connectionString, RetryPolicy retryPolicy, int connectionTimeoutMs, int sessionTimeoutMs)
{
// using the CuratorFrameworkFactory.builder() gives fine grained control
// over creation options. See the CuratorFrameworkFactory.Builder javadoc
// details
return CuratorFrameworkFactory.builder()
.connectString(connectionString)
.retryPolicy(retryPolicy)
.connectionTimeoutMs(connectionTimeoutMs)
.sessionTimeoutMs(sessionTimeoutMs)
// etc. etc.
.build();
}