您的位置:首页 > 其它

Curator框架

2016-02-12 23:16 423 查看

Curator简介

Curator是一个博物馆或者其它集合的监管者或者管理者,Curator有以下几个组件组成:

 Recipes: 实现了通用ZooKeeper的recipes, 该组件是在Framework组件为基础构建起来。

 Framework: 简化了用来ZooKeeper的高级API, 并增加了一些管理到ZooKeeper集群的连接和重试操作服务的新功能。

 Client: 是附加的ZooKeeper类(ZooKeeper客户端包)的一个替代品, 提供了一些底层处理和一些有用的工具类。

 Utilities: 各种ZooKeeper的工具类,在使用ZooKeeper时非常有用。

 Errors: 如何处理异常, 连接问题, 从异常中恢复等。

 Extensions: curator-recipe扩展服务功能,提供了一些其它的服务功能,比如服务发现、命名规范curator-x-name等。

Curator版本

当前curator有两个大的分支–2.x.x 和3.x.x,Curator 2.x.x兼容ZooKeeper3.4.x和ZooKeeper 3.5.x,Curator 3.x.x 仅仅与ZooKeeper 3.5.x兼容,它支持新的特性,比如动态配置等。

3.1 Curator编程简介

Curator使用 Fluent Style样式风格,如果你感觉怪怪的,你可以使用你中意的编程样式。Curator连接实例(CuratorFramework)是由Curator框架工厂类

(CuratorFrameworkFactory)里面。你可以使用下面代码创建一个ZooKeeper连接:

CuratorFrameworkFactory.newClient(zookeeperConnectionString, retryPolicy)


zookeeperConnectionString:是ZooKeeper服务器实例的ip:port配置,格式:

{ ip }:{ port },{ ip2}:{ port }。


retryPolicy: 重连策略。

对于大多数情况,你可以使用下面代码创建客户端连接。

RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3)
CuratorFramework client = CuratorFrameworkFactory.newClient(zookeeperConnectionString, retryPolicy);
client.start();


3.1.1 直接调用ZooKeeper

一旦你创建了一个CuratorFramework实例是,你能够直接调用ZooKeeper API创建ZooKeeper节点。

client.create().forPath("/my/path", myData)


由Curator管理ZooKeeper连接,便于应用重试连接策略。

3.1.2 技巧

3.1.2.1 分布式锁

分布式锁策略的核心代码如下所示:

InterProcessMutex lock = new InterProcessMutex(client, lockPath);
if ( lock.acquire(maxWait, waitUnit) ) {
try {
// do some work inside of the critical section here
}
finally{
lock.release();
}
}


3.1.2.2 Leader选择

Leader选择的核心代码如下所示:

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();


欢迎关注我的微信公众号

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ZooKeeper 框架 Curator