Zookeeper(持续更新) VIP-02 Zookeeper客户端使用与集群特性

本文涉及的产品
服务治理 MSE Sentinel/OpenSergo,Agent数量 不受限
简介: Curator 是一套由netflix 公司开源的,Java 语言编程的 ZooKeeper 客户端框架,Curator项目是现在ZooKeeper 客户端中使用最多,对ZooKeeper 版本支持最好的第三方客户端,并推荐使用,Curator 把我们平时常用的很多 ZooKeeper 服务开发功能做了封装,例如 Leader 选举、分布式计数器、分布式锁。这就减少了技术人员在使用 ZooKeeper 时的大部分底层细节开发工作。

VIP-02 Zookeeper客户端使用与集群特性


文章目录


正文

Zookeeper Java 客户端

项目构建

zookeeper 官方的客户端没有和服务端代码分离,他们为同一个jar 文件,所以我们直接引入

zookeeper的maven即可, 这里版本请保持与服务端版本一致,不然会有很多兼容性的问题

1 <dependency>
2 <groupId>org.apache.zookeeper</groupId>
3 <artifactId>zookeeper</artifactId>
4 <version>3.5.8</version>
5 </dependency>

创建客户端实例:

为了便于测试,直接在初始化方法中创建zookeeper实例

1 @Slf4j
2 public class ZookeeperClientTest {
3
4 private static final String ZK_ADDRESS="192.168.109.200:2181";
5
6 private static final int SESSION_TIMEOUT = 5000;
7
8 private static ZooKeeper zooKeeper;
9
10 private static final String ZK_NODE="/zk‐node";
11
12
13 @Before
14 public void init() throws IOException, InterruptedException {
15 final CountDownLatch countDownLatch=new CountDownLatch(1);
16 zooKeeper=new ZooKeeper(ZK_ADDRESS, SESSION_TIMEOUT, event ‐> {
17 if (event.getState()== Watcher.Event.KeeperState.SyncConnected &&
18 event.getType()== Watcher.Event.EventType.None){
19 countDownLatch.countDown();
20 log.info("连接成功!");
21 }
22 });
23 log.info("连接中....");
24 countDownLatch.await();
25 }
26 }

创建Zookeeper实例的方法:

1 ZooKeeper(String connectString, int sessionTimeout, Watcher watcher)
2 ZooKeeper(String connectString, int sessionTimeout, Watcher watcher, ZKClientC
onfig)
3 ZooKeeper(String connectString, int sessionTimeout, Watcher watcher, boolean c
anBeReadOnly, HostProvider)
4 ZooKeeper(String connectString, int sessionTimeout, Watcher watcher, boolean c
anBeReadOnly, HostProvider, ZKClientConfig)
5 ZooKeeper(String connectString, int sessionTimeout, Watcher watcher, boolean c
anBeReadOnly)
6 ZooKeeper(String connectString, int sessionTimeout, Watcher watcher, boolean c
anBeReadOnly, ZKClientConfig)
7 ZooKeeper(String connectString, int sessionTimeout, Watcher watcher, long, byt
e[])
8 ZooKeeper(String connectString, int sessionTimeout, Watcher watcher, long, byt
e[], boolean, HostProvider)
9 ZooKeeper(String connectString, int sessionTimeout, Watcher watcher, long, byt
e[], boolean, HostProvider, ZKClientConfig)
10 ZooKeeper(String connectString, int sessionTimeout, Watcher watcher, long, by
te[], boolean)

同步创建节点:

1 @Test
2 public void createTest() throws KeeperException, InterruptedException {
3 String path = zooKeeper.create(ZK_NODE, "data".getBytes(), ZooDefs.Ids.OPEN_A
CL_UNSAFE, CreateMode.PERSISTENT);
4 log.info("created path: {}",path);
5 }

异步创建节点:

1 @Test
2 public void createAsycTest() throws InterruptedException {
3 zooKeeper.create(ZK_NODE, "data".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,
4 CreateMode.PERSISTENT,
5 (rc, path, ctx, name) ‐> log.info("rc {},path {},ctx {},name
{}",rc,path,ctx,name),"context");
6 TimeUnit.SECONDS.sleep(Integer.MAX_VALUE);
7 }

修改节点数据

1 @Test
2 public void setTest() throws KeeperException, InterruptedException {
3
4 Stat stat = new Stat();
5 byte[] data = zooKeeper.getData(ZK_NODE, false, stat);
6 log.info("修改前: {}",new String(data));
7 zooKeeper.setData(ZK_NODE, "changed!".getBytes(), stat.getVersion());
8 byte[] dataAfter = zooKeeper.getData(ZK_NODE, false, stat);
9 log.info("修改后: {}",new String(dataAfter));
10 }

什么是 Curator

Curator 是一套由netflix 公司开源的,Java 语言编程的 ZooKeeper 客户端框架,Curator项目

是现在ZooKeeper 客户端中使用最多,对ZooKeeper 版本支持最好的第三方客户端,并推荐使

用,Curator 把我们平时常用的很多 ZooKeeper 服务开发功能做了封装,例如 Leader 选举、

分布式计数器、分布式锁。这就减少了技术人员在使用 ZooKeeper 时的大部分底层细节开发工

作。在会话重新连接、Watch 反复注册、多种异常处理等使用场景中,用原生的 ZooKeeper

处理比较复杂。而在使用 Curator 时,由于其对这些功能都做了高度的封装,使用起来更加简

单,不但减少了开发时间,而且增强了程序的可靠性。

Curator 实战

这里我们以 Maven 工程为例,首先要引入Curator 框架相关的开发包,这里为了方便测试引入

了junit ,lombok,由于Zookeeper本身以来了 log4j 日志框架,所以这里可以创建对应的

log4j配置文件后直接使用。 如下面的代码所示,我们通过将 Curator 相关的引用包配置到

Maven 工程的 pom 文件中,将 Curaotr 框架引用到工程项目里,在配置文件中分别引用了两

个 Curator 相关的包,第一个是 curator-framework 包,该包是对 ZooKeeper 底层 API 的一

些封装。另一个是 curator-recipes 包,该包封装了一些 ZooKeeper 服务的高级特性,如:

Cache 事件监听、选举、分布式锁、分布式 Barrier。

1 <dependency>
2 <groupId>org.apache.curator</groupId>
3 <artifactId>curator‐recipes</artifactId>
4 <version>5.0.0</version>
5 <exclusions>
6 <exclusion>
7 <groupId>org.apache.zookeeper</groupId>
8 <artifactId>zookeeper</artifactId>
9 </exclusion>
10 </exclusions>
11 </dependency>
12 <dependency>
13 <groupId>org.apache.zookeeper</groupId>
14 <artifactId>zookeeper</artifactId>
15 <version>3.5.8</version>
16 </dependency>
17 <dependency>
18 <groupId>junit</groupId>
19 <artifactId>junit</artifactId>
20 <version>4.13</version>
21 </dependency>
22 <dependency>
23 <groupId>org.projectlombok</groupId>
24 <artifactId>lombok</artifactId>
25 <version>1.18.12</version>
26 </dependency>

会话创建

要进行客户端服务器交互,第一步就要创建会话

Curator 提供了多种方式创建会话,比如用静态工厂方式创建:

1 // 重试策略
2 RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3)
3 CuratorFramework client = CuratorFrameworkFactory.newClient(zookeeperConnectio
nString, retryPolicy);
4 client.start();

或者使用 fluent 风格创建

1 RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
2 CuratorFramework client = CuratorFrameworkFactory.builder()
3 .connectString("192.168.128.129:2181")
4 .sessionTimeoutMs(5000) // 会话超时时间
5 .connectionTimeoutMs(5000) // 连接超时时间
6 .retryPolicy(retryPolicy)
7 .namespace("base") // 包含隔离名称
8 .build();
9 client.start();

这段代码的编码风格采用了流式方式,最核心的类是 CuratorFramework 类,该类的作用是定

义一个 ZooKeeper 客户端对象,并在之后的上下文中使用。在定义 CuratorFramework 对象

实例的时候,我们使用了 CuratorFrameworkFactory 工厂方法,并指定了 connectionString

服务器地址列表、retryPolicy 重试策略 、sessionTimeoutMs 会话超时时间、

connectionTimeoutMs 会话创建超时时间。下面我们分别对这几个参数进行讲解:

connectionString:服务器地址列表,在指定服务器地址列表的时候可以是一个地址,也可以

是多个地址。如果是多个地址,那么每个服务器地址列表用逗号分隔, 如

host1:port1,host2:port2,host3;port3 。

retryPolicy:重试策略,当客户端异常退出或者与服务端失去连接的时候,可以通过设置客户端

重新连接 ZooKeeper 服务端。而 Curator 提供了 一次重试、多次重试等不同种类的实现方

式。在 Curator 内部,可以通过判断服务器返回的 keeperException 的状态代码来判断是否进

行重试处理,如果返回的是 OK 表示一切操作都没有问题,而 SYSTEMERROR 表示系统或服务

端错误。

超时时间:Curator 客户端创建过程中,有两个超时时间的设置。一个是 sessionTimeoutMs

会话超时时间,用来设置该条会话在 ZooKeeper 服务端的失效时间。另一个是

connectionTimeoutMs 客户端创建会话的超时时间,用来限制客户端发起一个会话连接到接收

ZooKeeper 服务端应答的时间。sessionTimeoutMs 作用在服务端,而

connectionTimeoutMs 作用在客户端。

创建节点:

创建节点的方式如下面的代码所示,回顾我们之前课程中讲到的内容,描述一个节点要包括节点

的类型,即临时节点还是持久节点、节点的数据信息、节点是否是有序节点等属性和性质。

1 @Test
2 public void testCreate() throws Exception {
3 String path = curatorFramework.create().forPath("/curator‐node");
4 // curatorFramework.create().withMode(CreateMode.PERSISTENT).forPath("/curato
r‐node","some‐data".getBytes())
5 log.info("curator create node :{} successfully.",path);
6 }

在 Curator 中,可以使用 create 函数创建数据节点,并通过 withMode 函数指定节点类型

(持久化节点,临时节点,顺序节点,临时顺序节点,持久化顺序节点等),默认是持久化节

点,之后调用 forPath 函数来指定节点的路径和数据信息。

一次性创建带层级结构的节点

1 @Test
2 public void testCreateWithParent() throws Exception {
3 String pathWithParent="/node‐parent/sub‐node‐1";
4 String path = curatorFramework.create().creatingParentsIfNeeded().forPath(pat
hWithParent);
5 log.info("curator create node :{} successfully.",path);
6 }

获取数据

1 @Test
2 public void testGetData() throws Exception {
3 byte[] bytes = curatorFramework.getData().forPath("/curator‐node");
4 log.info("get data from node :{} successfully.",new String(bytes));
5 }

更新节点

我们通过客户端实例的 setData() 方法更新 ZooKeeper 服务上的数据节点,在setData 方法的

后边,通过 forPath 函数来指定更新的数据节点路径以及要更新的数据。

1 @Test
2 public void testSetData() throws Exception {
3 curatorFramework.setData().forPath("/curator‐node","changed!".getBytes());
4 byte[] bytes = curatorFramework.getData().forPath("/curator‐node");
5 log.info("get data from node /curator‐node :{} successfully.",new String(byte
s));
6 }

删除节点

1 @Test
2 public void testDelete() throws Exception {
3 String pathWithParent="/node‐parent";
4 curatorFramework.delete().guaranteed().deletingChildrenIfNeeded().forPath(pat
hWithParent);
5 }

guaranteed:该函数的功能如字面意思一样,主要起到一个保障删除成功的作用,其底层工作

方式是:只要该客户端的会话有效,就会在后台持续发起删除请求,直到该数据节点在

ZooKeeper 服务端被删除。

deletingChildrenIfNeeded:指定了该函数后,系统在删除该数据节点的时候会以递归的方式

直接删除其子节点,以及子节点的子节点。

异步接口

Curator 引入了BackgroundCallback 接口,用来处理服务器端返回来的信息,这个处理过程是

在异步线程中调用,默认在 EventThread 中调用,也可以自定义线程池。

1 public interface BackgroundCallback
2 {
3 /**
4 * Called when the async background operation completes
5 *
6 * @param client the client
7 * @param event operation result details
8 * @throws Exception errors
9 */
10 public void processResult(CuratorFramework client, CuratorEvent event) throw
s Exception;
11 }

如上接口,主要参数为 client 客户端, 和 服务端事件 event

inBackground 异步处理默认在EventThread中执行

1 @Test
2 public void test() throws Exception {
3 curatorFramework.getData().inBackground((item1, item2) ‐> {
4 log.info(" background: {}", item2);
5 }).forPath(ZK_NODE);
6
7 TimeUnit.SECONDS.sleep(Integer.MAX_VALUE);
8 }

指定线程池

1 @Test
2 public void test() throws Exception {
3 ExecutorService executorService = Executors.newSingleThreadExecutor();
4
5 curatorFramework.getData().inBackground((item1, item2) ‐> {
6 log.info(" background: {}", item2);
7 },executorService).forPath(ZK_NODE);
8
9 TimeUnit.SECONDS.sleep(Integer.MAX_VALUE);
10 }

Curator 监听器:

1 /**
2 * Receives notifications about errors and background events
3 */
4 public interface CuratorListener
5 {
6 /**
7 * Called when a background task has completed or a watch has triggered
8 *
9 * @param client client
10 * @param event the event
11 * @throws Exception any errors
12 */
13 public void eventReceived(CuratorFramework client, CuratorEvent event) throw
s Exception;
14 }

针对 background 通知和错误通知。使用此监听器之后,调用inBackground 方法会异步获得

监听

Curator Caches:

Curator 引入了 Cache 来实现对 Zookeeper 服务端事件监听,Cache 事件监听可以理解为一

个本地缓存视图与远程 Zookeeper 视图的对比过程。Cache 提供了反复注册的功能。Cache 分

为两类注册类型:节点监听和子节点监听。

node cache:

NodeCache 对某一个节点进行监听

1 public NodeCache(CuratorFramework client,
2 String path)
3 Parameters:
4 client ‐ the client
5 path ‐ path to cache

可以通过注册监听器来实现,对当前节点数据变化的处理

1 public void addListener(NodeCacheListener listener)
2 Add a change listener
3 Parameters:
4 listener ‐ the listener
1 @Slf4j
2 public class NodeCacheTest extends AbstractCuratorTest{
3
4 public static final String NODE_CACHE="/node‐cache";
5
6 @Test
7 public void testNodeCacheTest() throws Exception {
8
9 createIfNeed(NODE_CACHE);
10 NodeCache nodeCache = new NodeCache(curatorFramework, NODE_CACHE);
11 nodeCache.getListenable().addListener(new NodeCacheListener() {
12 @Override
13 public void nodeChanged() throws Exception {
14 log.info("{} path nodeChanged: ",NODE_CACHE);
15 printNodeData();
16 }
17 });
18
19 nodeCache.start();
20 }
21
22
23 public void printNodeData() throws Exception {
24 byte[] bytes = curatorFramework.getData().forPath(NODE_CACHE);
25 log.info("data: {}",new String(bytes));
26 }
27 }

path cache:

PathChildrenCache 会对子节点进行监听,但是不会对二级子节点进行监听,

1 public PathChildrenCache(CuratorFramework client,
2 String path,
3 boolean cacheData)
4 Parameters:
5 client ‐ the client
6 path ‐ path to watch
7 cacheData ‐ if true, node contents are cached in addition to the stat

可以通过注册监听器来实现,对当前节点的子节点数据变化的处理

1 public void addListener(PathChildrenCacheListener listener)
2 Add a change listener
3 Parameters:
4 listener ‐ the listener
1 @Slf4j
2 public class PathCacheTest extends AbstractCuratorTest{
3
4 public static final String PATH="/path‐cache";
5
6 @Test
7 public void testPathCache() throws Exception {
8
9 createIfNeed(PATH);
10 PathChildrenCache pathChildrenCache = new
PathChildrenCache(curatorFramework, PATH, true);
11 pathChildrenCache.getListenable().addListener(new
PathChildrenCacheListener() {
12 @Override
13 public void childEvent(CuratorFramework client, PathChildrenCacheEvent
event) throws Exception {
14 log.info("event: {}",event);
15 }
16 });
17
18 // 如果设置为true则在首次启动时就会缓存节点内容到Cache中
19 pathChildrenCache.start(true);
20 }
21 }

tree cache:

TreeCache 使用一个内部类TreeNode来维护这个一个树结构。并将这个树结构与ZK节点进行

了映射。所以TreeCache 可以监听当前节点下所有节点的事件。

1 public TreeCache(CuratorFramework client,
2 String path,
3 boolean cacheData)
4 Parameters:
5 client ‐ the client
6 path ‐ path to watch
7 cacheData ‐ if true, node contents are cached in addition to the stat

可以通过注册监听器来实现,对当前节点的子节点,及递归子节点数据变化的处理

1 public void addListener(TreeCacheListener listener)
2 Add a change listener
3 Parameters:
4 listener ‐ the listener
1 @Slf4j
2 public class TreeCacheTest extends AbstractCuratorTest{
3
4 public static final String TREE_CACHE="/tree‐path";
5
6 @Test
7 public void testTreeCache() throws Exception {
8 createIfNeed(TREE_CACHE);
9 TreeCache treeCache = new TreeCache(curatorFramework, TREE_CACHE);
10 treeCache.getListenable().addListener(new TreeCacheListener() {
11 @Override
12 public void childEvent(CuratorFramework client, TreeCacheEvent event) throws
Exception {
13 log.info(" tree cache: {}",event);
14 }
15 });
16 treeCache.start();
17 }
18 }

明天我们说Zookeeper 集群模式!!!

相关实践学习
基于MSE实现微服务的全链路灰度
通过本场景的实验操作,您将了解并实现在线业务的微服务全链路灰度能力。
相关文章
|
8天前
|
Java API Apache
ZooKeeper【基础 03】Java 客户端 Apache Curator 基础 API 使用举例(含源代码)
【4月更文挑战第11天】ZooKeeper【基础 03】Java 客户端 Apache Curator 基础 API 使用举例(含源代码)
24 11
|
9天前
|
存储 Java 网络安全
ZooKeeper【搭建 03】apache-zookeeper-3.6.0 伪集群版(一台服务器实现三个节点的ZooKeeper集群)
【4月更文挑战第10天】ZooKeeper【搭建 03】apache-zookeeper-3.6.0 伪集群版(一台服务器实现三个节点的ZooKeeper集群)
17 1
|
15天前
|
存储
ZooKeeper客户端常用命令
ZooKeeper客户端常用命令
25 1
|
29天前
|
算法 Java Linux
zookeeper单机伪集群集群部署
zookeeper单机伪集群集群部署
86 0
|
1月前
|
消息中间件 存储 Kafka
Kafka【环境搭建 02】kafka_2.11-2.4.1 基于 zookeeper 搭建高可用伪集群(一台服务器实现三个节点的 Kafka 集群)
【2月更文挑战第19天】Kafka【环境搭建 02】kafka_2.11-2.4.1 基于 zookeeper 搭建高可用伪集群(一台服务器实现三个节点的 Kafka 集群)
140 1
|
2月前
|
网络协议 中间件 数据库
Zookeeper学习系列【三】Zookeeper 集群架构、读写机制以及一致性原理(ZAB协议)
Zookeeper学习系列【三】Zookeeper 集群架构、读写机制以及一致性原理(ZAB协议)
96 0
|
2月前
|
网络协议
Zookeeper学习系列【二】Zookeeper 集群章节之集群搭建
Zookeeper学习系列【二】Zookeeper 集群章节之集群搭建
34 0
|
3月前
|
Java
搭建Zookeeper集群的搭建
搭建Zookeeper集群的搭建
36 1
|
3月前
|
安全 Java API
Zookeeper(持续更新) VIP-02 Zookeeper客户端使用与集群特性
2,/usr/local/data/zookeeper-3,/usr/local/data/zookeeper-4,在每个目录中创建文件。创建四个文件夹/usr/local/data/zookeeper-1,/usr/local/data/zookeeper-Follower:只能处理读请求,同时作为 Leader的候选节点,即如果Leader宕机,Follower节点。己对外提供服务的起始状态。E: 角色, 默认是 participant,即参与过半机制的角色,选举,事务请求过半提交,还有一个是。
|
3月前
Zookeeper的客户端的命令
Zookeeper的客户端的命令
18 0