持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第17天,点击查看活动详情
zookeeper 开源客户端curator介绍
原生zookeeper的API的存在一些不足之处:
- 连接对象是异步创建,需要手写代码,写等待逻辑
- zookeeper的连接没有自动重连和超时机制
- watcher是一次注册,只会生效一次,重复使用需重复注册
- 创建节点时不支持递归创建树形节点
有一个curator开源框架能解决这些问题,提供zooKeeper各种应用场景,比如:分布式锁服务、集群领导选举、分布式队列等功能的抽象封装,实现了Fluent风格的API接口。 curator开源框架的特点:
- 提供了session会话超时重连机制
- watcher支持反复注册,而不至于一次就实效
- 简化开发了api
- 遵循Fluent风格的API
- 提供了分布式锁服务、共享计数器、缓存机制等机制
maven依赖:
<groupId>org.apache.curator</groupId>
<artifactId>curator-framework</artifactId>
<version>版本</version>
连接
RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 5);
CuratorFramework client= CuratorFrameworkFactory.builder()
.connectString("192.168.0.1:2181")
.sessionTimeoutMs(5000)
.retryPolicy(retryPolicy)
.namespace("node")
.build()
RetryPolicy表示session重连策略,有三种类型:
- new RetryOneTime(5000) 表示5秒后只重连一次
- new RetryNTimes(3,5000) 表示每5秒重连一次,一共重连3次
- new RetryUntilElapsed(10000,3000) 表示每3秒重连一次,总等待时间超过10秒后停止重连
sessionTimeoutMs表示设置会话超时时间
新增节点
client = ...(连接代码)
client.create()
.withMode(CreateMode.PERSISTENT)
.withACL(ZooDefs.Ids.OPEN_ACL_UNSAFE)
.forPath("/node", "abc".getBytes());
withMode() 表示设置新增节点的类型
withACL() 表示设置节点的权限
更新节点
client = ...(连接代码)
client.setData()
.forPath("/node", "abcd".getBytes())
client.setData()
.withVersion(5)
.forPath("/node", "abcde".getBytes());
forPath() 表示设置节点的路径和数据
withVersion() 表示指定版本号更新
另外还可以用inBackground()方法指定异步进行更新数据
删除节点
client = ...(连接代码)
client.delete()
.forPath("/node");
client.delete()
.withVersion(5)
.forPath("/node");
client.delete()
.deletingChildrenIfNeeded()
.withVersion(5)
.forPath("/node");
withVersion() 表示指定版本号进行删除
deletingChildrenIfNeeded() 表示指定删除包含子节点的节点
另外也可以使用inBackground()方法指定异步删除