1. 简介
Curator是Netflix公司开源的一套zookeeper客户端框架,解决了很多Zookeeper客户端非常底层的细节开发工作,包括连接重连、反复注册Watcher和NodeExistsException异常等等。
Curator的maven依赖
<!-- 对zookeeper的底层api的一些封装 -->
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-framework</artifactId>
<version>2.12.0</version>
</dependency>
<!-- 封装了一些高级特性,如:Cache事件监听、选举、分布式锁、分布式Barrier -->
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-recipes</artifactId>
<version>2.12.0</version>
</dependency>
2. 基本API
2.1 创建会话
使用静态工程方法创建
RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
CuratorFramework client = CuratorFrameworkFactory.newClient("192.168.128.129:2181",
5000, 5000, retryPolicy);
其中RetryPolicy为重试策略,第一个参数为baseSleepTimeMs初始的sleep时间,用于计算之后的每次重试的sleep时间。第二个参数为maxRetries,最大重试次数。
使用Fluent风格api创建
RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
CuratorFramework client = CuratorFrameworkFactory.builder()
.connectString("192.168.128.129:2181")
.sessionTimeoutMs(5000) // 会话超时时间
.connectionTimeoutMs(5000) // 连接超时时间
.retryPolicy(retryPolicy)
.namespace("base") // 包含隔离名称
.build();
client.start();
2.2 创建数据节点
client.create().creatingParentContainersIfNeeded() // 递归创建所需父节点
.withMode(CreateMode.PERSISTENT) // 创建类型为持久节点
.forPath("/nodeA", "init".getBytes()); // 目录及内容
2.3 删除数据节点
client.delete()
.guaranteed() // 强制保证删除
.deletingChildrenIfNeeded() // 递归删除子节点
.withVersion(10086) // 指定删除的版本号
.forPath("/nodeA");
2.4 读取数据节点
读数据,返回值为byte[]
byte[] bytes = client.getData().forPath("/nodeA");
System.out.println(new String(bytes));
读stat
Stat stat = new Stat();
client.getData()
.storingStatIn(stat)
.forPath("/nodeA");
2.5 修改数据节点
client.setData()
.withVersion(10086) // 指定版本修改
.forPath("/nodeA", "data".getBytes());
2.6 事务
client.inTransaction().check().forPath("/nodeA")
.and()
.create().withMode(CreateMode.EPHEMERAL).forPath("/nodeB", "init".getBytes())
.and()
.create().withMode(CreateMode.EPHEMERAL).forPath("/nodeC", "init".getBytes())
.and()
.commit();
2.6 其他
client.checkExists() // 检查是否存在
.forPath("/nodeA");
client.getChildren().forPath("/nodeA"); // 获取子节点的路径
2.7 异步回调
异步创建节点
Executor executor = Executors.newFixedThreadPool(2);
client.create()
.creatingParentsIfNeeded()
.withMode(CreateMode.EPHEMERAL)
.inBackground((curatorFramework, curatorEvent) -> {
System.out.println(String.format("eventType:%s,resultCode:%s",curatorEvent.getType(),curatorEvent.getResultCode()));
},executor)
.forPath("path");
网友评论