Curator框架简单介绍和使用

[align=center][size=xx-large][b]Curator框架简单介绍和使用[/b][/size][/align]

[size=large][b]什么是Curator?[/b][/size]
Curator发音“kyoor͝ˌātər:”,是ZooKeeper的keeper。
“Guava is to Java what Curator is to ZooKeeper”
---Patrick Hunt, ZooKeeper commiter
[size=large]使用Curator[/size]
[*]获取一个连接
如果你仅需要一个ZooKeeper连接管理和重试策略的包装,使用curator-framework的包就行。Curator 连接实例(CuratorFramework)可从CuratorFrameworkFactory得到。一个
CuratorFramework对应ZooKeeper集群,代码看起来像这样:
RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3)
CuratorFramework client = CuratorFrameworkFactory.newClient(zookeeperConnectionString, retryPolicy);
client.start();

client必须启动,当不再使用时关闭

[*]直接调用ZooKeeper
一旦有了 CuratorFramework实例,你可以直接调用ZooKeeper
client.create().forPath("/my/path", myData)

这样一来Curator就会管理ZooKeeper连接,并且当连接错误时会有重试操作。

[size=large]秘诀[/size]
[*]分布式锁
InterProcessMutex lock = new InterProcessMutex(client, lockPath);
if ( lock.acquire(maxWait, waitUnit) )
{
try
{
// do some work inside of the critical section here
}
finally
{
lock.release();
}
}


[*]领导选举
LeaderSelectorListener listener = new LeaderSelectorListenerAdapter()
{
public void takeLeadership(CuratorFramework client) throws Exception
{
// this callback will get called when you are the leader
// do whatever leader work you need to and only exit
// this method when you want to relinquish leadership
}
}

LeaderSelector selector = new LeaderSelector(client, path, listener);
selector.autoRequeue(); // not required, but this is behavior that you will probably expect
selector.start();


[size=large]公共类ZKPaths[/size]
静态的方法,操作ZooKeeper ZNode paths
[*]getNodeFromPath : 给一个全路径,返回节点名称。例子 "/one/two/three" 返回 three
[*]mkdirs:创建path里的所有节点。
[*]getSortedChildren:返回有序seq的子集
[*]makePath:合并path和node。

代码例子:
[url]https://github.com/apache/curator/tree/master/curator-examples[/url]


参考
[url]https://cwiki.apache.org/confluence/display/CURATOR/Tech+Notes[/url]

[url]http://curator.apache.org/index.html[/url]

你可能感兴趣的:(Java)