一、简介
curator是Netflix公司开源的一个Zookeeper client library,用于简化zookeeper客户端编程,包含一下几个模块:
curator-client - zookeeper client封装,用于取代原生的zookeeper客户端,提供一些非常有用的客户端特性
curator-framework - zookeeper api的高层封装,大大简化zookeeper客户端编程,添加了例如zookeeper连接管理、重试机制等
curator-recipes - zookeeper recipes 基于curator-framework的实现(除2PC以外)
从github和maven上的消息来看,1.0.1的版本已经十分稳定,相对应的zk版本是3.3.x,还在开发中的版本是1.1.x,对应的版本是zk3.4.x。
二、依赖
- < dependency >
- < groupId > com.netflix.curator </ groupId >
- < artifactId > curator-framework </ artifactId >
- < version > 1.0.1 </ version >
- </ dependency >
三、代码讲解
以下代码以CuratorFramework为例:
- public static void main(String[] args) throws Exception {
- String path = "/test_path" ;
- CuratorFramework client = CuratorFrameworkFactory.builder().connectString( "zookeeper.n.miliao.com:2181" ).namespace( "/brokers" ).retryPolicy( new RetryNTimes(Integer.MAX_VALUE, 1000 )).connectionTimeoutMs( 5000 ).build();
- // 启动 上面的namespace会作为一个最根的节点在使用时自动创建
- client.start();
- // 创建一个节点
- client.create().forPath( "/head" , new byte [ 0 ]);
- // 异步地删除一个节点
- client.delete().inBackground().forPath( "/head" );
- // 创建一个临时节点
- client.create().withMode(CreateMode.EPHEMERAL_SEQUENTIAL).forPath( "/head/child", new byte [ 0 ]);
- // 取数据
- client.getData().watched().inBackground().forPath( "/test" );
- // 检查路径是否存在
- client.checkExists().forPath(path);
- // 异步删除
- client.delete().inBackground().forPath( "/head" );
- // 注册观察者,当节点变动时触发
- client.getData().usingWatcher( new Watcher() {
- @Override
- public void process(WatchedEvent event) {
- System.out.println( "node is changed" );
- }
- }).inBackground().forPath( "/test" );
- // 结束使用
- client.close();
- }
四、方法说明
create(): 发起一个create操作. 可以组合其他方法 (比如mode 或background) 最后以forPath()方法结尾
delete(): 发起一个删除操作. 可以组合其他方法(version 或background) 最后以forPath()方法结尾
checkExists(): 发起一个检查ZNode 是否存在的操作. 可以组合其他方法(watch 或background) 最后以forPath()方法结尾
getData(): 发起一个获取ZNode数据的操作. 可以组合其他方法(watch, background 或get stat) 最后以forPath()方法结尾
setData(): 发起一个设置ZNode数据的操作. 可以组合其他方法(version 或background) 最后以forPath()方法结尾
getChildren(): 发起一个获取ZNode子节点的操作. 可以组合其他方法(watch, background 或get stat) 最后以forPath()方法结尾
inTransaction(): 发起一个ZooKeeper事务. 可以组合create, setData, check, 和/或delete 为一个操作, 然后commit() 提交
五、五四陈点评
相比zookeeper常用的zkClient的确是平易近人了,上手容易,理解轻松,语法优美,至于是不是各种情况都处理了,还得靠实践检验。