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

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 分
为两类注册类型:节点监听和子节点监听。

相关文章:

  • node 后端和浏览器前端,有关 RSA 非对称加密的完整实践, 前后端匹配的代码演示
  • 从零开始实现大语言模型(十六):加载开源大语言模型参数
  • Flink 并行度的设置
  • 给个人程序加上MCP翅膀
  • 基于labview的声音采集、存储、处理
  • GitHub 趋势日报 (2025年05月17日)
  • C++(243~263)STL常用算法、遍历算法(for_each,Transform)、查找算法、拷贝和替换、常用算术生成,常用集合算法。
  • C++学习:六个月从基础到就业——C++17:if/switch初始化语句
  • 【随机过程】贝叶斯估计
  • 【计算机网络】第一章:计算机网络体系结构
  • TIMER免疫浸润分析
  • 轻量级视频剪辑方案:FFmpeg图形化工具体验
  • 国内人工智能行业研究报告 投资要点
  • Spring Cloud 技术实战
  • 非线性1 修改
  • 23种设计模式解释+记忆
  • 5.18本日总结
  • VMware虚拟机磁盘扩容与LVM分区操作指南
  • GC全场景分析
  • Redis进阶知识
  • 海南乐城管理局原局长贾宁已赴省政协工作,曾从河南跨省任职
  • 以军在加沙北部和南部展开大规模地面行动
  • 香港今年新股集资额已超600亿港元,暂居全球首位
  • 国宝文物子弹库帛书二、三卷从美启程,18日凌晨抵京
  • 技术派|威胁F-35、击落“死神”,胡塞武装防空战力如何?
  • 我使馆就中国公民和企业遭不公正待遇向菲方持续提出严正交涉