Curator框架简单介绍和使用
程序员文章站
2022-07-13 14:54:45
...
Curator框架简单介绍和使用
什么是Curator?
Curator发音“kyoor͝ˌātər:”,是ZooKeeper的keeper。
“Guava is to Java what Curator is to ZooKeeper”
---Patrick Hunt, ZooKeeper commiter
使用Curator
CuratorFramework对应ZooKeeper集群,代码看起来像这样:
RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3) CuratorFramework client = CuratorFrameworkFactory.newClient(zookeeperConnectionString, retryPolicy); client.start();
client必须启动,当不再使用时关闭
client.create().forPath("/my/path", myData)
这样一来Curator就会管理ZooKeeper连接,并且当连接错误时会有重试操作。
秘诀
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();
公共类ZKPaths
静态的方法,操作ZooKeeper ZNode paths
代码例子:
https://github.com/apache/curator/tree/master/curator-examples
参考
https://cwiki.apache.org/confluence/display/CURATOR/Tech+Notes
http://curator.apache.org/index.html