一、基本依赖
Curator是Netflix公司开源的一个Zookeeper客户端,目前由Apache进行维护。与Zookeeper原生客户端相比,Curator的抽象层次更高,功能也更加丰富,是目前Zookeeper使用范围最广的Java客户端。本篇文章主要讲解其基本使用,项目采用Maven构建,以单元测试的方法进行讲解,相关依赖如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| <dependencies> <dependency> <groupId>org.apache.curator</groupId> <artifactId>curator-framework</artifactId> <version>4.0.0</version> </dependency> <dependency> <groupId>org.apache.curator</groupId> <artifactId>curator-recipes</artifactId> <version>4.0.0</version> </dependency> <dependency> <groupId>org.apache.zookeeper</groupId> <artifactId>zookeeper</artifactId> <version>3.4.13</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> </dependencies>
|
完整源码见本仓库: https://github.com/myhhub/BigData-Notes/tree/master/code/Zookeeper/curator
二、客户端相关操作
2.1 创建客户端实例
这里使用@Before
在单元测试执行前创建客户端实例,并使用@After
在单元测试后关闭客户端连接。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| public class BasicOperation {
private CuratorFramework client = null; private static final String zkServerPath = "192.168.0.226:2181"; private static final String nodePath = "/hadoop/yarn";
@Before public void prepare() { RetryPolicy retryPolicy = new RetryNTimes(3, 5000); client = CuratorFrameworkFactory.builder() .connectString(zkServerPath) .sessionTimeoutMs(10000).retryPolicy(retryPolicy) .namespace("workspace").build(); client.start(); }
@After public void destroy() { if (client != null) { client.close(); } } }
|
2.2 重试策略
在连接Zookeeper时,Curator提供了多种重试策略以满足各种需求,所有重试策略均继承自RetryPolicy
接口,如下图:
这些重试策略类主要分为以下两类:
- RetryForever :代表一直重试,直到连接成功;
- SleepingRetry : 基于一定间隔时间的重试。这里以其子类
ExponentialBackoffRetry
为例说明,其构造器如下:
1 2 3 4 5 6
|
ExponentialBackoffRetry(int baseSleepTimeMs, int maxRetries, int maxSleepMs)
|
2.3 判断服务状态
1 2 3 4 5
| @Test public void getStatus() { CuratorFrameworkState state = client.getState(); System.out.println("服务是否已经启动:" + (state == CuratorFrameworkState.STARTED)); }
|
三、节点增删改查
3.1 创建节点
1 2 3 4 5 6 7 8
| @Test public void createNodes() throws Exception { byte[] data = "abc".getBytes(); client.create().creatingParentsIfNeeded() .withMode(CreateMode.PERSISTENT) .withACL(ZooDefs.Ids.OPEN_ACL_UNSAFE) .forPath(nodePath, data); }
|
创建时可以指定节点类型,这里的节点类型和Zookeeper原生的一致,全部类型定义在枚举类CreateMode
中:
1 2 3 4 5 6 7 8 9 10 11
| public enum CreateMode { PERSISTENT (0, false, false), PERSISTENT_SEQUENTIAL (2, false, true), EPHEMERAL (1, true, false), EPHEMERAL_SEQUENTIAL (3, true, true); .... }
|
2.2 获取节点信息
1 2 3 4 5 6 7
| @Test public void getNode() throws Exception { Stat stat = new Stat(); byte[] data = client.getData().storingStatIn(stat).forPath(nodePath); System.out.println("节点数据:" + new String(data)); System.out.println("节点信息:" + stat.toString()); }
|
如上所示,节点信息被封装在Stat
类中,其主要属性如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| public class Stat implements Record { private long czxid; private long mzxid; private long ctime; private long mtime; private int version; private int cversion; private int aversion; private long ephemeralOwner; private int dataLength; private int numChildren; private long pzxid; ... }
|
每个属性的含义如下:
状态属性 |
说明 |
czxid |
数据节点创建时的事务ID |
ctime |
数据节点创建时的时间 |
mzxid |
数据节点最后一次更新时的事务ID |
mtime |
数据节点最后一次更新时的时间 |
pzxid |
数据节点的子节点最后一次被修改时的事务ID |
cversion |
子节点的更改次数 |
version |
节点数据的更改次数 |
aversion |
节点的ACL的更改次数 |
ephemeralOwner |
如果节点是临时节点,则表示创建该节点的会话的SessionID;如果节点是持久节点,则该属性值为0 |
dataLength |
数据内容的长度 |
numChildren |
数据节点当前的子节点个数 |
2.3 获取子节点列表
1 2 3 4 5 6 7
| @Test public void getChildrenNodes() throws Exception { List<String> childNodes = client.getChildren().forPath("/hadoop"); for (String s : childNodes) { System.out.println(s); } }
|
2.4 更新节点
更新时可以传入版本号也可以不传入,如果传入则类似于乐观锁机制,只有在版本号正确的时候才会被更新。
1 2 3 4 5 6
| @Test public void updateNode() throws Exception { byte[] newData = "defg".getBytes(); client.setData().withVersion(0) .forPath(nodePath, newData); }
|
2.5 删除节点
1 2 3 4 5 6 7 8
| @Test public void deleteNodes() throws Exception { client.delete() .guaranteed() .deletingChildrenIfNeeded() .withVersion(0) .forPath(nodePath); }
|
2.6 判断节点是否存在
1 2 3 4 5 6
| @Test public void existNode() throws Exception { Stat stat = client.checkExists().forPath(nodePath + "aa/bb/cc"); System.out.println("节点是否存在:" + !(stat == null)); }
|
三、监听事件
3.1 创建一次性监听
和Zookeeper原生监听一样,使用usingWatcher
注册的监听是一次性的,即监听只会触发一次,触发后就销毁。示例如下:
1 2 3 4 5 6 7 8 9
| @Test public void DisposableWatch() throws Exception { client.getData().usingWatcher(new CuratorWatcher() { public void process(WatchedEvent event) { System.out.println("节点" + event.getPath() + "发生了事件:" + event.getType()); } }).forPath(nodePath); Thread.sleep(1000 * 1000); }
|
3.2 创建永久监听
Curator还提供了创建永久监听的API,其使用方式如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| @Test public void permanentWatch() throws Exception { NodeCache nodeCache = new NodeCache(client, nodePath); nodeCache.start(true); nodeCache.getListenable().addListener(new NodeCacheListener() { public void nodeChanged() { ChildData currentData = nodeCache.getCurrentData(); if (currentData != null) { System.out.println("节点路径:" + currentData.getPath() + "数据:" + new String(currentData.getData())); } } }); Thread.sleep(1000 * 1000); }
|
3.3 监听子节点
这里以监听/hadoop
下所有子节点为例,实现方式如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| @Test public void permanentChildrenNodesWatch() throws Exception {
PathChildrenCache childrenCache = new PathChildrenCache(client, "/hadoop", true);
childrenCache.start(StartMode.POST_INITIALIZED_EVENT);
List<ChildData> childDataList = childrenCache.getCurrentData(); System.out.println("当前数据节点的子节点列表:"); childDataList.forEach(x -> System.out.println(x.getPath()));
childrenCache.getListenable().addListener(new PathChildrenCacheListener() { public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) { switch (event.getType()) { case INITIALIZED: System.out.println("childrenCache初始化完成"); break; case CHILD_ADDED: System.out.println("增加子节点:" + event.getData().getPath()); break; case CHILD_REMOVED: System.out.println("删除子节点:" + event.getData().getPath()); break; case CHILD_UPDATED: System.out.println("被修改的子节点的路径:" + event.getData().getPath()); System.out.println("修改后的数据:" + new String(event.getData().getData())); break; } } }); Thread.sleep(1000 * 1000); }
|