Zookeeper客户端Curator---Getting Started
先说个小插曲,前几天有个网站转载我的文章没有署名作者,我有点不开心就给他们留言了,然后今天一看他们把文章删了。其实我的意思并不是你允许转载,我想表达的是我的付出需要被尊重。也不知道是谁的错~
==================================
官网上的入门教程非常简单,如下:
学习Zookeeper
使用Curator的用户默认是了解Zookeeper的,Zookeeper的入门在这里:http://zookeeper.apache.org/doc/current/zookeeperStarted.html
使用Curator
Curator的jar包可以从Maven中央仓库获得。各种工具罗列在主页上 main page。Maven,Gradle,Ant等用户可以轻松地将Curator包含进其构建脚本中。
大多数用户希望使用Curator的预制recipes(基于framework,提供高级特性),所以,curator-recipes是个正确的选择。如果您只想使用Zookeeper添加连接管理和重试策略的封装好的工具,那么使用curator-framework。
获取一个连接
Curator使用流式风格。如果你之前没有使用过这个,可能看起来很奇怪,因此建议您事先熟悉一下风格。ps:其实就是链式风格(Demo demo = new DemoBuilder().first().second().last().build();)
Curator连接的实例(CuratorFramework)来自于CuratorFrameworkFactory。每一个你连接的Zookeeper集群只需要一个CuratorFramework实例:
CuratorFrameworkFactory.newClient(zookeeperConnectionString, retryPolicy)
这将会使用默认值去连接一个Zookeeper集群。唯一需要指定的是 重试策略。大多数情况下,您应该使用:
RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3)
CuratorFramework client = CuratorFrameworkFactory.newClient(zookeeperConnectionString, retryPolicy);
client.start();
客户端必须启动(不再使用必须关闭)
直接调用Zookeeper
一旦你有一个CuratorFramework实例,你可以直接调用ZooKeeper,就像使用ZooKeeper中提供的原始Zookeeper对象一样。例如:
client.create().forPath("/my/path", myData)
这里的好处是:由CuratorFramework管理Zookeeper连接,并且当出现连接问题时会重试。
Recipes(高级特性)
分布式锁
InterProcessMutex lock = new InterProcessMutex(client, lockPath);
if ( lock.acquire(maxWait, waitUnit) )
{
try
{
// do some work inside of the critical section here
}
finally
{
lock.release();
}
}
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();
更多的特性翻译接下来的文章会有。
一个小例子
导入的jar包:

curator-recipes这个包没用到,ZkClient那个包是另外一个客户端,这里也用不到,除了这两个其他都是要导入的
package zookeeper.curator; import java.util.List; import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.api.BackgroundCallback;
import org.apache.curator.framework.api.CuratorEvent;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat; public class CuratorBase { private static String connectString = "192.168.127.129:2181,192.168.127.130:2181,192.168.127.131:2181"; public static void main(String[] args) throws Exception { // 重试策略,初试时间1s,重试3次
RetryPolicy policy = new ExponentialBackoffRetry(1000, 3); CuratorFramework curator = CuratorFrameworkFactory.newClient(connectString, policy);
curator.start();
//获取状态
System.out.println(curator.getState()); System.out.println("============Create=============");
//创建节点
String cPath1 = curator.create()
.creatingParentsIfNeeded()
.withMode(CreateMode.PERSISTENT).inBackground(new BackgroundCallback() { @Override
public void processResult(CuratorFramework curatorFramework, CuratorEvent event) throws Exception {
System.out.println(">>>>>>>>>>>>>>>>>>>>>>>");
System.out.println("Code:" + event.getResultCode());
System.out.println("Name:" + event.getName());
System.out.println("Path:" + event.getPath());
System.out.println("Type:" + event.getType());
System.out.println("CurrentThread:" + Thread.currentThread().getName());
System.out.println("<<<<<<<<<<<<<<<<<<<<<<<");
}
}).forPath("/root/rt", "123".getBytes());
System.out.println("MainThread:" + Thread.currentThread().getName());
Thread.sleep(2000); //暂停2s,为了等异步执行完,否则下面会报错:KeeperErrorCode = NoNode for /root/rr
System.out.println(cPath1);
String cPath2 = curator.create().withMode(CreateMode.PERSISTENT).forPath("/root/rr", "456".getBytes());
System.out.println(cPath2);
String cPath3 = curator.create().withMode(CreateMode.PERSISTENT).forPath("/root/re", "789".getBytes());
System.out.println(cPath3); System.out.println("===========getData==============");
//获取节点数值
byte[] data = curator.getData().forPath("/root/rt");
System.out.println("数值:" + new String(data)); System.out.println("============setData=============");
//修改节点数据
Stat stat = curator.setData().forPath("/root/rt", "abc".getBytes());
System.out.println(stat); System.out.println("============getChildren=============");
//获取子节点
List<String> childPath = curator.getChildren().forPath("/root");
for (String path : childPath) {
System.out.println(path + ":" + new String(curator.getData().forPath("/root/" + path)));
} System.out.println("============Detele=============");
//删除节点
curator.delete().forPath("/root/rt");
System.out.println("是否存在:" + curator.checkExists().forPath("/root/rt"));
curator.delete().deletingChildrenIfNeeded().forPath("/root");
System.out.println("是否存在:" + curator.checkExists().forPath("/root")); curator.close(); //关闭 }
}
log4j2.xml
<?xml version="1.0" encoding="UTF-8"?>
<Configuration monitorInterval="1800"> <Filter type="ThresholdFilter" level="trace"/> <Appenders>
<Console name="console" target="SYSTEM_OUT">
<!--控制台只输出level及以上级别的信息(onMatch),其他的直接拒绝(onMismatch)-->
<ThresholdFilter level="trace" onMatch="ACCEPT" onMismatch="DENY"/>
<PatternLayout pattern="%d %-5p [%t] %C{2} (%F:%L) - %m%n"/>
</Console>
</Appenders>
<Loggers>
<Root level="WARN">
<!-- TRACE < DEBUG < INFO < WARN < ERROR < FATAL
-->
<AppenderRef ref="console"/>
</Root>
</Loggers>
</Configuration>
结果:
STARTED
============Create=============
MainThread:main
>>>>>>>>>>>>>>>>>>>>>>>
Code:0
Name:/root/rt
Path:/root/rt
Type:CREATE
CurrentThread:main-EventThread
<<<<<<<<<<<<<<<<<<<<<<<
null
/root/rr
/root/re
===========getData==============
数值:123
============setData=============
51539607575,51539607578,1502067208571,1502067210604,1,0,0,0,3,0,51539607575 ============getChildren=============
rr:456
rt:abc
re:789
============Detele=============
是否存在:null
是否存在:null
关于代码也没啥可解释的,顾名思义。
比如creatingParentsIfNeeded(),就是如果需要的话就创建父节点,这个方法的好处是可以递归创建节点。
inBackground(new BackgroundCallback(){})这个就是异步创建节点啦,不阻塞线程。
更多内容以后再说。
Zookeeper客户端Curator---Getting Started的更多相关文章
- Zookeeper客户端Curator使用详解
Zookeeper客户端Curator使用详解 前提 最近刚好用到了zookeeper,做了一个基于SpringBoot.Curator.Bootstrap写了一个可视化的Web应用: zookeep ...
- 转:Zookeeper客户端Curator使用详解
原文:https://www.jianshu.com/p/70151fc0ef5d Zookeeper客户端Curator使用详解 前提 最近刚好用到了zookeeper,做了一个基于SpringBo ...
- Zookeeper客户端Curator基本API
在使用zookeper的时候一般不使用原生的API,Curator,解决了很多Zookeeper客户端非常底层的细节开发工作,包括连接重连.反复注册Watcher和NodeExistsExceptio ...
- Zookeeper客户端Curator的使用,简单高效
Curator是Netflix公司开源的一个Zookeeper客户端,与Zookeeper提供的原生客户端相比,Curator的抽象层次更高,简化了Zookeeper客户端的开发量. 1.引入依赖: ...
- zookeeper(六):Zookeeper客户端Curator的API使用详解
简介 Curator是Netflix公司开源的一套zookeeper客户端框架,解决了很多Zookeeper客户端非常底层的细节开发工作,包括连接重连.反复注册Watcher和NodeExistsEx ...
- 7.5 zookeeper客户端curator的基本使用 + zkui
使用zookeeper原生API实现一些复杂的东西比较麻烦.所以,出现了两款比较好的开源客户端,对zookeeper的原生API进行了包装:zkClient和curator.后者是Netflix出版的 ...
- 聊聊、Zookeeper 客户端 Curator
[Curator] 和 ZkClient 一样,Curator 也是开源客户端,Curator 是 Netflix 公司开源的一套框架. <dependency> <groupI ...
- Zookeeper客户端 CuratorFramework使用
CuratorFramework使用 跟着实例学习ZooKeeper的用法: Curator框架应用 ZooKeeper客户端Curator使用一 创建连接
- 八:Zookeeper开源客户端Curator的api测试
curator是Netflix公司开源的一套ZooKeeper客户端,Curator解决了很多ZooKeeper客户端非常底层的细节开发工作.包括连接重连,反复注册Watcher等.实现了Fluent ...
- zookeeper客户端使用第三方(Curator)封装的Api操作节点
1.为什么使用Curator? Curator本身是Netflix公司开源的zookeeper客户端: Curator 提供了各种应用场景的实现封装: curator-framework 提供了f ...
随机推荐
- Mongodb副本集+分片集群环境部署记录
前面详细介绍了mongodb的副本集和分片的原理,这里就不赘述了.下面记录Mongodb副本集+分片集群环境部署过程: MongoDB Sharding Cluster,需要三种角色: Shard S ...
- D. Vasya and Triangle
传送门 [http://codeforces.com/contest/1030/problem/D] 题意 在第一象限,x,y得坐标上限是n,m,再给你个k,让你找3个整数点,使得围成面积等于(n*m ...
- 毕业设计 之 二 PHP集成环境(Dreamweaver)使用
毕业设计 之 二 PHP学习笔记(一) 作者:20135216 平台:windows10 软件:XAMPP,DreamWeaver 一.环境搭建 1.XAMPP下载安装 XAMPP是PHP.MySQL ...
- 实例详解Java中如何对方法进行调用
原文源自http://www.jb51.net/article/73827.htm 方法调用Java支持两种调用方法的方式,根据方法是否返回值来选择. 当程序调用一个方法时,程序的控制权交给了被调用的 ...
- SpringBoot初识
作用 SpringBoot是为了简化Spring应用的创建.运行.调试.部署等等而出现的,使用它可以专注业务开发,不需要太多的xml的配置. 核心功能 1.内嵌Servlet容器(tomcat.jet ...
- Selenium的自我总结2_元素基本操作
对于Selenium的基本元素的操作,就自己的了解做了一个基本的介绍,这篇直接上代码,针对一个页面如何操作写了些基本的操作脚本,希望对初学者有一定的帮助,也希望通过这些总结让自己有一些清晰的认识和了解 ...
- Linux 下如何知道是否有人在使坏?
在 Linux 下查看用户的行为,不仅仅是网管要做的事,也是开发人员所应该具备的基本技能之一.为什么呢?因为有时其他同事在做一些很消耗资源的事情,比如在编译大型程序,可能会导致服务器变得很慢,从而影响 ...
- ACDsee的安装过程
http://www.ddooo.com/softdown/76175.htm ACDSee 18中文版安装教程: 1.ACDSee 18分为32位和64位版本,我们先选择合适系统的中文版本开始安装, ...
- super 使用以及原理
用super也很久了,但是一直没有关注过他的原理.最近开始越来越多关注python更底层的实现和奇技淫巧.看到该方法越发使用得多所以也研究了一波 平时单继承可能是我们遇到最多的情况.无非就是类似情况. ...
- ultraEdit MAC 破解方法
安装了个UltraEdit 但是需要验证码,太麻烦了,破解方法: 拷贝附件(command +c )然后在MAC的底下点击访达==>应用程序==>UltraEdit==>右击 显示包 ...