当前位置: 首页 > backend >正文

Zookeeper入门(三)

Zookeeper Java 客户端

项目构建

ookeeper 官方的客户端没有和服务端代码分离,他们为同一个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)

connectString:

ZooKeeper服务器列表,由英文逗号分开的host:port字符串组成,
每一个都代表一台ZooKeeper机器,如,
host1:port1,host2:port2,host3:port3。另外,也可以在connectString中设
置客户端连接上ZooKeeper
后的根目录,方法是在host:port字符串之后添加上这个根目录,例
如,host1:port1,host2:port2,host3:port3/zk-base,这样就指定了该客户端连
接上ZooKeeper服务器之后,所有对ZooKeeper
的操作,都会基于这个根目录。例如,客户端对/sub-node 的操作,最终创建
/zk-node/sub-node, 这个目录也叫Chroot,即客户端隔离命名空间。

sessionTimeout 

会话的超时时间,是一个以“毫秒”为单位的整型值。在ZooKeeper中有
会话的概念,在一个会话周期内,ZooKeeper客户端和服务器之间会通过心跳

测机制来维持会话的有效性,一旦在sessionTimeout时间内没有进行有效
的心跳检测,会话就会失效。

watcher

ZooKeeper允许
客户端在构造方法中传入一个接口 watcher (org.apache. zookeeper.
Watcher)的实现类对象来作为默认的 Watcher事件通知处理器。当然,该参
数可以设置为null 以表明不需要设置默认的 Watcher处理器。

canBeReadOnly

这是一个boolean类型的参数,用于标识当前会话是否支持“read-only(只
读)”模式。默认情况下,在ZooKeeper集群中,一个机器如果和集群中过半

以上机器失去了网络连接,那么这个机器将不再处理客户端请求(包括读写请
求)。但是在某些使用场景下,当ZooKeeper服务器发生此类故障的时候,我

还是希望ZooKeeper服务器能够提供读服务(当然写服务肯定无法提供)——
这就是 ZooKeeper的“read-only”模式。

sessionId和 ses
sionPasswd

分别代表会话ID和会话秘钥。这两个参数能够唯一确定一个会话,同时客户
端使用这两个参数可以实现客户端会话复用,从而达到恢复会话的效果。具体
使用方法是,第一次连接上ZooKeeper服务器时,通过调用ZooKeeper对象

例的以下两个接口,即可获得当前会话的ID和秘钥:
long getSessionId();
byte[]getSessionPasswd( );
荻取到这两个参数值之后,就可以在下次创建ZooKeeper对象实例的时候传
入构造方法了

同步创建节点:
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 Caches:

Curator 引入了 Cache 来实现对 Zookeeper 服务端事件监听,Cache 事件监听可以理解为一
个本地缓存视图与远程 Zookeeper 视图的对比过程。Cache 提供了反复注册的功能。Cache 分
为两类注册类型:节点监听和子节点监听。

http://www.xdnf.cn/news/7038.html

相关文章:

  • 《Vite 报错》ReferenceError: module is not defined in ES module scope
  • 影刀处理 Excel:智能工具带来的高效变革
  • 广域网学习
  • 数据结构与算法——栈和队列
  • Python字符串格式化(一):三种经典格式化方法
  • 从零开始实现大语言模型(十六):加载开源大语言模型参数
  • 《Python星球日记》 第87天:什么是大语言模型 LLM?
  • 1_Spring 【IOC容器的创建】
  • 深入了解linux系统—— 基础IO(下)
  • 【QGIS二次开发】地图编辑-08
  • tauri2项目使用sidcar嵌入可执行文件并使用命令行调用
  • 实战设计模式之状态模式
  • 互联网大厂Java面试场景:从Spring Boot到分布式缓存技术的探讨
  • 十一、STM32入门学习之FREERTOS移植
  • React 19 中的useRef得到了进一步加强。
  • ngx_http_proxy_protocol_vendor_module 模块
  • 【Linux】进程的基本概念
  • 虚幻引擎5-Unreal Engine笔记之Pawn与胶囊体的关系
  • 【android bluetooth 协议分析 01】【HCI 层介绍 5】【SetEventMask命令介绍】
  • Elasticsearch 初步认识
  • 用 UniApp 构建习惯打卡 App —— HabitLoop 开发记
  • 【cursor】有效解决
  • Denoising Score Matching with Langevin Dynamics
  • 【HarmonyOS 5开发入门】DevEco Studio安装配置完全指南
  • Flink 的窗口机制
  • 【ant design】ant-design-vue 4.0实现主题色切换
  • 【软考 McCabe度量法】
  • 深入理解指针(6)
  • 基因编辑根治胰腺癌-陈墨仙
  • Raft 协议:分布式一致性算法的核心思想