Curator-Client使用(三)

重要说明

Curator Client是一个低级的API,所以官方强烈建议使用CuratorFramework,而不是直接使用CuratorZookeeperClient

存在即合理,看一下都有啥用处?

介绍

CuratorZookeeperClient 包装原生java client,并使得client更容易,少出错,提供了下面一些特性:

  • 持续的连接管理

    ZooKeeper本身会有好多关于连接管理的警告(查阅一下ZK FAQ)。CuratorZookeeperClient 会自动的处理。

  • Operation retry utilities

  • Test ZooKeeper server

提供的方法列表

Method Description
Constructor Create a connection to a given ZooKeeper cluster. You can pass in an optional watcher. You must provide a Retry Policy.
getZooKeeper() Returns the managed ZooKeeper instance. IMPORTANT NOTES: a) It takes time for a connection to complete, you should validate that the connection is complete before using other methods. b) The managed ZooKeeper instance can change due to certain events. Do not hold on to the instance for long periods. Always get a fresh reference from getZooKeeper().
isConnected() Returns true if the ZooKeeper client is currently connected (this can always change due to errors)
blockUntilConnectedOrTimedOut() A convenience method that blocks until the initial connection is successful or times out
close() Close the connection
setRetryPolicy() Change the retry policy
newRetryLoop() Allocate a new Retry Loop - see details below

重试操作

由于多种多样的原因,一些操作会失败,对这些操作进行重试操作是必要的。重试机制提供:每个操作应该被一个retry loop 包起来。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
RetryLoop retryLoop = client.newRetryLoop();
while ( retryLoop.shouldContinue() )
{
try
{
// perform your work
...
// it's important to re\-get the ZK instance as there may have been an error and the instance was re\-created
ZooKeeper zk = client.getZookeeper();
retryLoop.markComplete();
}
catch ( Exception e )
{
retryLoop.takeException(e);
}
}

retryLoop.markComplete();如果没有异常,会改变retry中的状态,退出循环。

为了方便起见,RetryLoop有一个静态方法,添加Callable,当执行重试的时候回调。 例如

1
2
3
4
5
6
7
8
9
RetryLoop.callWithRetry(client, new Callable<Void>()
{
@Override
public Void call() throws Exception
{
// do your work here - it will get retried if needed
return null;
}
});

重试策略

RetryPolicy是接口,包含唯一方法public boolean allowRetry(int retryCount, long elapsedTimeMs);

当retry发生,会调用allowRetry()方法,根据既定的策略,判断当前这次retry是否可以执行,如果可以,继续执行,否则抛出InterruptedException退出。

org.apache.curator.retry包下几种策略

Policy Name Description
ExponentialBackoffRetry Retry policy that retries a set number of times with increasing sleep time between retries
RetryNTimes Retry policy that retries a max number of times
RetryOneTime A retry policy that retries only once
RetryUntilElapsed A retry policy that retries until a given amount of time elapses
坚持技术分享,您的支持将鼓励我继续创作!