抱歉,您的浏览器无法访问本站
本页面需要浏览器支持(启用)JavaScript
了解详情 >

摘要:无。

环境

Windows 10 企业版 LTSC 21H2
Java 1.8
Maven 3.6.3
Spring 5.3.31
Spring Boot 2.7.18
ZooKeeper 3.8.4
Curator 5.7.1

1 连接管理

1.1 创建连接

连接实例通过CuratorFrameworkFactory创建,每个ZooKeeper集群只需要一个CuratorFramework对象:

java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 创建重试策略,基础等待1000毫秒,重试3次
RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
// 创建客户端
CuratorFramework client = CuratorFrameworkFactory.builder()
.connectString("127.0.0.1:2181") // 集群地址
.sessionTimeoutMs(60 * 1000) // 会话超时时间
.connectionTimeoutMs(15 * 1000) // 连接超时时间
.retryPolicy(retryPolicy) // 重试策略
.canBeReadOnly(true) // 出现网络分区时,是否允许使用只读模式提供服务
.build();
// 启动客户端,异步执行
client.start();
// 关闭客户端,必须手动关闭
client.close();

1.2 监听连接状态

连接状态:

  • CONNECTED:首次成功连接到服务器时发送,只会收到一次。
  • SUSPENDED:连接丢失,会话挂起。
  • RECONNECTED:连接重新建立。
  • LOST:会话过期或者连接超时。
  • READ_ONLY:出现网络分区,会话进入只读模式提供服务。

使用ConnectionStateListener可以监听连接状态:

java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
client.getConnectionStateListenable().addListener((curatorFramework, newState) -> {
switch (newState) {
case CONNECTED:
System.out.println("会话建立");
break;
case SUSPENDED:
System.out.println("会话挂起");
break;
case RECONNECTED:
System.out.println("会话重连");
break;
case LOST:
System.out.println("会话丢失");
break;
case READ_ONLY:
System.out.println("会话只读");
break;
}
});

1.3 重试策略

Curator内置多种重试策略,用于在连接故障或会话过期时自动重试操作。

重试策略通过RetryPolicy接口抽象,默认提供了多种实现:

  • RetryOneTime:重试一次,属于RetryNTimes特例。
  • RetryNTimes:重试N次。
  • ExponentialBackoffRetry:重试固定次数,等待时间指数级增长,指数退避重试。
  • BoundedExponentialBackoffRetry:重试固定次数,等待时间指数级增长,等待时间有上限,有界指数退避重试。
  • RetryUntilElapsed:重试直到总耗时超过指定上限。
  • RetryForever:重试直到成功。

2 节点操作

2.1 创建节点

使用create()方法获取CreateBuilder构建器,用于创建节点,支持链式调用配置各种选项。

常用方法:

java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// 父节点不存在则自动创建持久模式父节点
public ProtectACLCreateModeStatPathAndBytesable<String> creatingParentsIfNeeded();
// 父节点不存在则自动创建容器模式父节点,如果不支持容器模式,则使用持久模式
public ProtectACLCreateModeStatPathAndBytesable<String> creatingParentContainersIfNeeded();
// 设置节点模式
public ACLBackgroundPathAndBytesable<String> withMode(CreateMode mode);
// 回填状态信息
public ACLBackgroundPathAndBytesable<String> storingStatIn(Stat stat);
// 设置ACL权限
public BackgroundPathAndBytesable<String> withACL(List<ACL> aclList);
// 设置ACL权限,设置创建的父节点是否使用指定的ACL权限
public BackgroundPathAndBytesable<String> withACL(List<ACL> aclList, boolean applyToParents);
// 创建节点,指定路径
public String forPath(String path) throws Exception;
// 创建节点,指定路径和数据
public String forPath(String path, byte[] data) throws Exception;

节点模式:

  • CreateMode.PERSISTENT:持久节点,创建后一直存在,除非主动删除,默认模式
  • CreateMode.PERSISTENT_SEQUENTIAL:持久有序节点,节点名自动追加递增序号
  • CreateMode.EPHEMERAL:临时节点,断开连接时自动删除
  • CreateMode.EPHEMERAL_SEQUENTIAL:临时有序节点,断开连接时自动删除,节点名自动追加递增序号
  • CreateMode.CONTAINER:容器节点,当没有任何子节点时,服务端会自动将其删除
  • CreateMode.PERSISTENT_WITH_TTL:带TTL的持久节点,指定时间内无修改则自动删除
  • CreateMode.PERSISTENT_SEQUENTIAL_WITH_TTL:带TTL的持久有序节点,节点名自动追加递增序号,指定时间内无修改则自动删除

示例:

java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 创建持久节点
client.create()
.creatingParentsIfNeeded()
.withMode(CreateMode.PERSISTENT)
.forPath("/user/zs", "张三".getBytes());

// 创建持久有序节点,读取状态信息
Stat stat = new Stat();
client.create()
.storingStatIn(stat)
.withMode(CreateMode.PERSISTENT_SEQUENTIAL)
.forPath("/user/ls", "李四".getBytes());
System.out.println("版本号:" + stat.getVersion());
System.out.println("数据长度:" + stat.getDataLength());

2.2 读取节点

2.2.1 读取节点数据

使用getData()方法获取GetDataBuilder构建器,用于读取节点数据。

常用方法:

java
1
2
3
4
// 回填状态信息
public WatchPathable<byte[]> storingStatIn(Stat stat);
// 读取节点数据
public byte[] forPath(String path) throws Exception;

示例:

java
1
2
3
4
5
6
7
8
9
10
// 读取节点数据
byte[] data = client.getData().forPath("/user/zs");
System.out.println("节点数据:" + new String(data));

// 读取节点数据和状态信息
Stat stat = new Stat();
byte[] dataWithStat = client.getData().storingStatIn(stat).forPath("/user/zs");
System.out.println("节点数据:" + new String(dataWithStat));
System.out.println("版本号:" + stat.getVersion());
System.out.println("数据长度:" + stat.getDataLength());

2.2.2 读取子节点列表

使用getChildren()方法获取GetChildrenBuilder构建器,用于读取子节点列表。

常用方法:

java
1
2
3
4
// 回填状态信息
public WatchPathable<List<String>> storingStatIn(Stat stat);
// 获取子节点列表
public List<String> forPath(String path) throws Exception;

示例:

java
1
2
3
4
5
6
7
8
9
// 获取子节点列表
List<String> children = client.getChildren().forPath("/user");
System.out.println("子节点列表:" + children);

// 获取子节点列表和状态信息
Stat childStat = new Stat();
List<String> childrenWithStat = client.getChildren().storingStatIn(childStat).forPath("/user");
System.out.println("子节点列表:" + childrenWithStat);
System.out.println("子节点数量:" + childStat.getNumChildren());

2.2.3 检查节点是否存在

使用checkExists()方法获取ExistsBuilder构建器,用于检查节点是否存在。

常用方法:

java
1
2
// 检查节点是否存在,返回状态信息
public Stat forPath(String path) throws Exception;

示例:

java
1
2
3
4
5
6
7
// 检查节点是否存在
Stat existStat = client.checkExists().forPath("/user/zs");
if (existStat != null) {
System.out.println("节点存在,版本号:" + existStat.getVersion());
} else {
System.out.println("节点不存在");
}

2.3 更新节点

使用setData()方法获取SetDataBuilder构建器,用于更新节点数据。

常用方法:

java
1
2
3
4
5
6
// 基于版本号更新
public BackgroundPathAndBytesable<Stat> withVersion(int version);
// 更新节点数据,使用默认数据
public Stat forPath(String path) throws Exception;
// 更新节点数据,指定数据
public Stat forPath(String path, byte[] data) throws Exception;

示例:

java
1
2
3
4
5
6
7
8
// 更新节点数据
client.setData().forPath("/user/zs", "更新数据".getBytes());

// 基于版本号更新
Stat stat = new Stat();
client.getData().storingStatIn(stat).forPath("/user/zs");
int version = stat.getVersion();
client.setData().withVersion(version).forPath("/user/zs", "比较版本更新数据".getBytes());

2.4 删除节点

使用delete()方法获取DeleteBuilder构建器,用于删除节点。

常用方法:

java
1
2
3
4
5
6
7
8
// 保证删除,如果因为连接断开导致删除失败,会自动重试删除
public ChildrenDeletable guaranteed();
// 递归删除节点,同时删除子节点
public BackgroundVersionable deletingChildrenIfNeeded();
// 基于版本号删除
public BackgroundPathable<Void> withVersion(int version);
// 删除节点,节点不能有子节点
public Void forPath(String path) throws Exception;

示例:

java
1
2
3
4
5
6
7
8
// 删除节点
client.delete().forPath("/user/zs");

// 基于版本号删除
Stat stat = new Stat();
client.getData().storingStatIn(stat).forPath("/user/ls");
int version = stat.getVersion();
client.delete().withVersion(version).forPath("/user/ls");

评论