Zookeeper Java 客户端 ——Apache Curator

This commit is contained in:
罗祥 2019-06-03 15:41:59 +08:00
parent 75c92fdb48
commit 47b4eef1a2

View File

@ -1,5 +1,6 @@
# Zookeeper Java 客户端 ——Apache Curator # Zookeeper Java 客户端 ——Apache Curator
<nav>
<nav>
<a href="#一基本依赖">一、基本依赖</a><br/> <a href="#一基本依赖">一、基本依赖</a><br/>
<a href="#二客户端相关操作">二、客户端相关操作</a><br/> <a href="#二客户端相关操作">二、客户端相关操作</a><br/>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#21-创建客户端实例">2.1 创建客户端实例</a><br/> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#21-创建客户端实例">2.1 创建客户端实例</a><br/>
@ -18,317 +19,318 @@
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#33-监听子节点">3.3 监听子节点</a><br/> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#33-监听子节点">3.3 监听子节点</a><br/>
</nav> </nav>
## 一、基本依赖 ## 一、基本依赖
Curator是Netflix公司开源的一个Zookeeper客户端目前由Apache进行维护。与Zookeeper原生客户端相比Curator的抽象层次更高功能也更加丰富是Zookeeper使用范围最广的Java客户端。本片文章主要讲解其基本使用以下项目采用Maven构建以单元测试的方法进行讲解相关依赖如下 Curator是Netflix公司开源的一个Zookeeper客户端目前由Apache进行维护。与Zookeeper原生客户端相比Curator的抽象层次更高功能也更加丰富是目前Zookeeper使用范围最广的Java客户端。本篇文章主要讲解其基本使用项目采用Maven构建以单元测试的方法进行讲解相关依赖如下
```xml ```xml
<dependencies> <dependencies>
<dependency> <!--Curator相关依赖-->
<groupId>org.apache.curator</groupId> <dependency>
<artifactId>curator-framework</artifactId> <groupId>org.apache.curator</groupId>
<version>4.0.0</version> <artifactId>curator-framework</artifactId>
</dependency> <version>4.0.0</version>
<dependency> </dependency>
<groupId>org.apache.curator</groupId> <dependency>
<artifactId>curator-recipes</artifactId> <groupId>org.apache.curator</groupId>
<version>4.0.0</version> <artifactId>curator-recipes</artifactId>
</dependency> <version>4.0.0</version>
<dependency> </dependency>
<groupId>org.apache.zookeeper</groupId> <dependency>
<artifactId>zookeeper</artifactId> <groupId>org.apache.zookeeper</groupId>
<version>3.4.13</version> <artifactId>zookeeper</artifactId>
</dependency> <version>3.4.13</version>
<!--单元测试相关依赖--> </dependency>
<dependency> <!--单元测试相关依赖-->
<groupId>junit</groupId> <dependency>
<artifactId>junit</artifactId> <groupId>junit</groupId>
<version>4.12</version> <artifactId>junit</artifactId>
</dependency> <version>4.12</version>
</dependencies> </dependency>
``` </dependencies>
```
> 完整源码见本仓库: https://github.com/heibaiying/BigData-Notes/tree/master/code/Zookeeper/curator
> 完整源码见本仓库: https://github.com/heibaiying/BigData-Notes/tree/master/code/Zookeeper/curator
## 二、客户端相关操作
## 二、客户端相关操作
### 2.1 创建客户端实例
### 2.1 创建客户端实例
这里使用`@Before`在单元测试执行前创建客户端实例,并使用`@After`在单元测试后关闭客户端连接。
这里使用`@Before`在单元测试执行前创建客户端实例,并使用`@After`在单元测试后关闭客户端连接。
```java
public class BasicOperation { ```java
public class BasicOperation {
private CuratorFramework client = null;
private static final String zkServerPath = "192.168.0.226:2181"; private CuratorFramework client = null;
private static final String nodePath = "/hadoop/yarn"; private static final String zkServerPath = "192.168.0.226:2181";
private static final String nodePath = "/hadoop/yarn";
@Before
public void prepare() { @Before
// 重试策略 public void prepare() {
RetryPolicy retryPolicy = new RetryNTimes(3, 5000); // 重试策略
client = CuratorFrameworkFactory.builder() RetryPolicy retryPolicy = new RetryNTimes(3, 5000);
.connectString(zkServerPath) client = CuratorFrameworkFactory.builder()
.sessionTimeoutMs(10000).retryPolicy(retryPolicy) .connectString(zkServerPath)
.namespace("workspace").build(); //指定命名空间后client的所有路径操作都会以/workspace开头 .sessionTimeoutMs(10000).retryPolicy(retryPolicy)
client.start(); .namespace("workspace").build(); //指定命名空间后client的所有路径操作都会以/workspace开头
} client.start();
}
@After
public void destroy() { @After
if (client != null) { public void destroy() {
client.close(); if (client != null) {
} client.close();
} }
} }
``` }
```
### 2.2 重试策略
### 2.2 重试策略
在连接Zookeeper服务时候Curator提供了多种重试策略以满足各种需求所有重试策略继承自`RetryPolicy`接口,如下图:
在连接Zookeeper时Curator提供了多种重试策略以满足各种需求所有重试策略均继承自`RetryPolicy`接口,如下图:
<div align="center"> <img src="https://github.com/heibaiying/BigData-Notes/blob/master/pictures/curator-retry-policy.png"/> </div>
<div align="center"> <img src="https://github.com/heibaiying/BigData-Notes/blob/master/pictures/curator-retry-policy.png"/> </div>
而这些重试策略类又分为两大类别:
这些重试策略类主要分为以下两类:
+ RetryForever :代表一直重试,直到连接成功;
+ SleepingRetry 基于一定间隔时间的重试,这里以其子类`ExponentialBackoffRetry`为例说明,其构造器如下: + **RetryForever** :代表一直重试,直到连接成功;
+ **SleepingRetry** 基于一定间隔时间的重试。这里以其子类`ExponentialBackoffRetry`为例说明,其构造器如下:
```java
/** ```java
* @param baseSleepTimeMs 重试之间等待的初始时间 /**
* @param maxRetries 最大重试次数 * @param baseSleepTimeMs 重试之间等待的初始时间
* @param maxSleepMs 每次重试间隔的最长睡眠时间(毫秒) * @param maxRetries 最大重试次数
*/ * @param maxSleepMs 每次重试间隔的最长睡眠时间(毫秒)
ExponentialBackoffRetry(int baseSleepTimeMs, int maxRetries, int maxSleepMs) */
``` ExponentialBackoffRetry(int baseSleepTimeMs, int maxRetries, int maxSleepMs)
### 2.3 判断服务状态 ```
### 2.3 判断服务状态
```scala
@Test ```scala
public void getStatus() { @Test
CuratorFrameworkState state = client.getState(); public void getStatus() {
System.out.println("服务是否已经启动:" + (state == CuratorFrameworkState.STARTED)); CuratorFrameworkState state = client.getState();
} System.out.println("服务是否已经启动:" + (state == CuratorFrameworkState.STARTED));
``` }
```
## 三、节点增删改查
## 三、节点增删改查
### 3.1 创建节点
### 3.1 创建节点
```java
@Test ```java
public void createNodes() throws Exception { @Test
byte[] data = "abc".getBytes(); public void createNodes() throws Exception {
client.create().creatingParentsIfNeeded() byte[] data = "abc".getBytes();
.withMode(CreateMode.PERSISTENT) //节点类型 client.create().creatingParentsIfNeeded()
.withACL(ZooDefs.Ids.OPEN_ACL_UNSAFE) .withMode(CreateMode.PERSISTENT) //节点类型
.forPath(nodePath, data); .withACL(ZooDefs.Ids.OPEN_ACL_UNSAFE)
} .forPath(nodePath, data);
``` }
```
创建时可以指定节点类型这里的节点类型和Zookeeper原生的一致全部定义在枚举类`CreateMode`中:
创建时可以指定节点类型这里的节点类型和Zookeeper原生的一致全部类型定义在枚举类`CreateMode`中:
```java
public enum CreateMode { ```java
// 永久节点 public enum CreateMode {
PERSISTENT (0, false, false), // 永久节点
//永久有序节点 PERSISTENT (0, false, false),
PERSISTENT_SEQUENTIAL (2, false, true), //永久有序节点
// 临时节点 PERSISTENT_SEQUENTIAL (2, false, true),
EPHEMERAL (1, true, false), // 临时节点
// 临时有序节点 EPHEMERAL (1, true, false),
EPHEMERAL_SEQUENTIAL (3, true, true); // 临时有序节点
.... EPHEMERAL_SEQUENTIAL (3, true, true);
} ....
``` }
```
### 2.2 获取节点信息
### 2.2 获取节点信息
```scala
@Test ```scala
public void getNode() throws Exception { @Test
Stat stat = new Stat(); public void getNode() throws Exception {
byte[] data = client.getData().storingStatIn(stat).forPath(nodePath); Stat stat = new Stat();
System.out.println("节点数据:" + new String(data)); byte[] data = client.getData().storingStatIn(stat).forPath(nodePath);
System.out.println("节点信息:" + stat.toString()); System.out.println("节点数据:" + new String(data));
} System.out.println("节点信息:" + stat.toString());
``` }
```
如上所示,节点信息被封装在`Stat`类中,其主要属性如下:
如上所示,节点信息被封装在`Stat`类中,其主要属性如下:
```java
public class Stat implements Record { ```java
private long czxid; public class Stat implements Record {
private long mzxid; private long czxid;
private long ctime; private long mzxid;
private long mtime; private long ctime;
private int version; private long mtime;
private int cversion; private int version;
private int aversion; private int cversion;
private long ephemeralOwner; private int aversion;
private int dataLength; private long ephemeralOwner;
private int numChildren; private int dataLength;
private long pzxid; private int numChildren;
... private long pzxid;
} ...
``` }
```
每个属性的含义如下:
每个属性的含义如下:
| **状态属性** | **说明** |
| -------------- | ------------------------------------------------------------ | | **状态属性** | **说明** |
| czxid | 数据节点创建时的事务ID | | -------------- | ------------------------------------------------------------ |
| ctime | 数据节点创建时的时间 | | czxid | 数据节点创建时的事务ID |
| mzxid | 数据节点最后一次更新时的事务ID | | ctime | 数据节点创建时的时间 |
| mtime | 数据节点最后一次更新时的时间 | | mzxid | 数据节点最后一次更新时的事务ID |
| pzxid | 数据节点的子节点最后一次被修改时的事务ID | | mtime | 数据节点最后一次更新时的时间 |
| cversion | 子节点的更改次数 | | pzxid | 数据节点的子节点最后一次被修改时的事务ID |
| version | 节点数据的更改次数 | | cversion | 子节点的更改次数 |
| aversion | 节点的ACL的更改次数 | | version | 节点数据的更改次数 |
| ephemeralOwner | 如果节点是临时节点则表示创建该节点的会话的SessionID如果节点是持久节点则该属性值为0 | | aversion | 节点的ACL的更改次数 |
| dataLength | 数据内容的长度 | | ephemeralOwner | 如果节点是临时节点则表示创建该节点的会话的SessionID如果节点是持久节点则该属性值为0 |
| numChildren | 数据节点当前的子节点个数 | | dataLength | 数据内容的长度 |
| numChildren | 数据节点当前的子节点个数 |
### 2.3 获取子节点列表
### 2.3 获取子节点列表
```java
@Test ```java
public void getChildrenNodes() throws Exception { @Test
List<String> childNodes = client.getChildren().forPath("/hadoop"); public void getChildrenNodes() throws Exception {
for (String s : childNodes) { List<String> childNodes = client.getChildren().forPath("/hadoop");
System.out.println(s); for (String s : childNodes) {
} System.out.println(s);
} }
``` }
```
### 2.4 更新节点
### 2.4 更新节点
更新时可以传入版本号也可以不传入,如果传入则类似于乐观锁机制,只有在版本号正确的时候才会被更新。
更新时可以传入版本号也可以不传入,如果传入则类似于乐观锁机制,只有在版本号正确的时候才会被更新。
```scala
@Test ```scala
public void updateNode() throws Exception { @Test
byte[] newData = "defg".getBytes(); public void updateNode() throws Exception {
client.setData().withVersion(0) // 传入版本号,如果版本号错误则拒绝更新操作,并抛出BadVersion异常 byte[] newData = "defg".getBytes();
.forPath(nodePath, newData); client.setData().withVersion(0) // 传入版本号,如果版本号错误则拒绝更新操作,并抛出BadVersion异常
} .forPath(nodePath, newData);
``` }
```
### 2.5 删除节点
### 2.5 删除节点
```java
@Test ```java
public void deleteNodes() throws Exception { @Test
client.delete() public void deleteNodes() throws Exception {
.guaranteed() // 如果删除失败,那么在会继续执行,直到成功 client.delete()
.deletingChildrenIfNeeded() // 如果有子节点,则递归删除 .guaranteed() // 如果删除失败,那么在会继续执行,直到成功
.withVersion(0) // 传入版本号,如果版本号错误则拒绝删除操作,并抛出BadVersion异常 .deletingChildrenIfNeeded() // 如果有子节点,则递归删除
.forPath(nodePath); .withVersion(0) // 传入版本号,如果版本号错误则拒绝删除操作,并抛出BadVersion异常
} .forPath(nodePath);
``` }
```
### 2.6 判断节点是否存在
### 2.6 判断节点是否存在
```java
@Test ```java
public void existNode() throws Exception { @Test
// 如果节点存在则返回其状态信息如果不存在则为null public void existNode() throws Exception {
Stat stat = client.checkExists().forPath(nodePath + "aa/bb/cc"); // 如果节点存在则返回其状态信息如果不存在则为null
System.out.println("节点是否存在:" + !(stat == null)); Stat stat = client.checkExists().forPath(nodePath + "aa/bb/cc");
} System.out.println("节点是否存在:" + !(stat == null));
``` }
```
## 三、监听事件
## 三、监听事件
### 3.1 创建一次性监听
### 3.1 创建一次性监听
和Zookeeper原生监听一样使用`usingWatcher`注册的监听是一次性的,即监听只会触发一次,触发后就销毁。示例如下:
和Zookeeper原生监听一样使用`usingWatcher`注册的监听是一次性的,即监听只会触发一次,触发后就销毁。示例如下:
```java
@Test ```java
public void DisposableWatch() throws Exception { @Test
client.getData().usingWatcher(new CuratorWatcher() { public void DisposableWatch() throws Exception {
public void process(WatchedEvent event) { client.getData().usingWatcher(new CuratorWatcher() {
System.out.println("节点" + event.getPath() + "发生了事件:" + event.getType()); public void process(WatchedEvent event) {
} System.out.println("节点" + event.getPath() + "发生了事件:" + event.getType());
}).forPath(nodePath); }
Thread.sleep(1000 * 1000); //休眠以观察测试效果 }).forPath(nodePath);
} Thread.sleep(1000 * 1000); //休眠以观察测试效果
``` }
```
### 3.2 创建永久监听
### 3.2 创建永久监听
Curator还提供了创建永久监听的API其使用方式如下
Curator还提供了创建永久监听的API其使用方式如下
```java
@Test ```java
public void permanentWatch() throws Exception { @Test
// 使用NodeCache包装节点对其注册的监听作用于节点且是永久性的 public void permanentWatch() throws Exception {
NodeCache nodeCache = new NodeCache(client, nodePath); // 使用NodeCache包装节点对其注册的监听作用于节点且是永久性的
// 通常设置为true, 代表创建nodeCache时,就去获取对应节点的值并缓存 NodeCache nodeCache = new NodeCache(client, nodePath);
nodeCache.start(true); // 通常设置为true, 代表创建nodeCache时,就去获取对应节点的值并缓存
nodeCache.getListenable().addListener(new NodeCacheListener() { nodeCache.start(true);
public void nodeChanged() { nodeCache.getListenable().addListener(new NodeCacheListener() {
ChildData currentData = nodeCache.getCurrentData(); public void nodeChanged() {
if (currentData != null) { ChildData currentData = nodeCache.getCurrentData();
System.out.println("节点路径:" + currentData.getPath() + if (currentData != null) {
"数据:" + new String(currentData.getData())); System.out.println("节点路径:" + currentData.getPath() +
} "数据:" + new String(currentData.getData()));
} }
}); }
Thread.sleep(1000 * 1000); //休眠以观察测试效果 });
} Thread.sleep(1000 * 1000); //休眠以观察测试效果
``` }
```
### 3.3 监听子节点
### 3.3 监听子节点
这里以监听`/hadoop`下所有子节点为例,实现方式如下:
这里以监听`/hadoop`下所有子节点为例,实现方式如下:
```scala
@Test ```scala
public void permanentChildrenNodesWatch() throws Exception { @Test
public void permanentChildrenNodesWatch() throws Exception {
// 第三个参数代表除了节点状态外,是否还缓存节点内容
PathChildrenCache childrenCache = new PathChildrenCache(client, "/hadoop", true); // 第三个参数代表除了节点状态外,是否还缓存节点内容
/* PathChildrenCache childrenCache = new PathChildrenCache(client, "/hadoop", true);
* StartMode代表初始化方式: /*
* NORMAL: 异步初始化 * StartMode代表初始化方式:
* BUILD_INITIAL_CACHE: 同步初始化 * NORMAL: 异步初始化
* POST_INITIALIZED_EVENT: 异步并通知,初始化之后会触发INITIALIZED事件 * BUILD_INITIAL_CACHE: 同步初始化
*/ * POST_INITIALIZED_EVENT: 异步并通知,初始化之后会触发INITIALIZED事件
childrenCache.start(StartMode.POST_INITIALIZED_EVENT); */
childrenCache.start(StartMode.POST_INITIALIZED_EVENT);
List<ChildData> childDataList = childrenCache.getCurrentData();
System.out.println("当前数据节点的子节点列表:"); List<ChildData> childDataList = childrenCache.getCurrentData();
childDataList.forEach(x -> System.out.println(x.getPath())); System.out.println("当前数据节点的子节点列表:");
childDataList.forEach(x -> System.out.println(x.getPath()));
childrenCache.getListenable().addListener(new PathChildrenCacheListener() {
public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) { childrenCache.getListenable().addListener(new PathChildrenCacheListener() {
switch (event.getType()) { public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) {
case INITIALIZED: switch (event.getType()) {
System.out.println("childrenCache初始化完成"); case INITIALIZED:
break; System.out.println("childrenCache初始化完成");
case CHILD_ADDED: break;
// 需要注意的是: 即使是之前已经存在的子节点也会触发该监听因为会把该子节点加入childrenCache缓存中 case CHILD_ADDED:
System.out.println("增加子节点:" + event.getData().getPath()); // 需要注意的是: 即使是之前已经存在的子节点也会触发该监听因为会把该子节点加入childrenCache缓存中
break; System.out.println("增加子节点:" + event.getData().getPath());
case CHILD_REMOVED: break;
System.out.println("删除子节点:" + event.getData().getPath()); case CHILD_REMOVED:
break; System.out.println("删除子节点:" + event.getData().getPath());
case CHILD_UPDATED: break;
System.out.println("被修改的子节点的路径:" + event.getData().getPath()); case CHILD_UPDATED:
System.out.println("修改后的数据:" + new String(event.getData().getData())); System.out.println("被修改的子节点的路径:" + event.getData().getPath());
break; System.out.println("修改后的数据:" + new String(event.getData().getData()));
} break;
} }
}); }
Thread.sleep(1000 * 1000); //休眠以观察测试效果 });
} Thread.sleep(1000 * 1000); //休眠以观察测试效果
}
``` ```