import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.TreeCache;
import org.apache.curator.framework.recipes.cache.TreeCacheEvent;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.List;
// Curator是Apache提供的一套操作Zookeeper的客户端框架
// 封装了Zookeeper的基本操作,并且还提供了一些高级特性
public class CuratorDemo {
private CuratorFramework client;
// 开启客户端
@Before
public void startClient() {
// 重试策略 - 如果连接Zookeeper失败,可以试图重新连接
// baseSleepTimeMs - 重试的间隔时间
// maxRetries - 重试的最大次数
RetryPolicy rp = new ExponentialBackoffRetry(3000, 3);
// 开启客户端
client = CuratorFrameworkFactory.newClient(
"10.42.122.250:2181,10.42.126.252:2181,10.42.160.37:2181", rp);
client.start();
}
// 创建节点
@Test
public void createNode() throws Exception {
client.create()
.creatingParentsIfNeeded()
.withMode(CreateMode.PERSISTENT)
.forPath("/video/movie/chinese", "test".getBytes());
}
// 修改节点数据
@Test
public void setData() throws Exception {
client.setData()
.withVersion(-1).forPath("/video", "video servers".getBytes());
}
// 获取节点数据
@Test
public void getData() throws Exception {
byte[] data = client.getData().forPath("/video");
System.out.println(new String(data));
}
// 获取子节点
@Test
public void getChildren() throws Exception {
List<String> cs = client.getChildren().forPath("/video");
for (String c : cs) {
System.out.println(c);
}
}
// 删除节点
@Test
public void deleteNode() throws Exception {
client.delete()
.deletingChildrenIfNeeded()
.withVersion(-1)
.forPath("/video");
}
// 判断节点是否存在
@Test
public void exists() throws Exception {
Stat s = client.checkExists().forPath("/video");
System.out.println(s != null);
}
// 监控
@Test
public void watch() throws Exception {
// 表示会获取并且监听/log节点以及所有的子节点
TreeCache cache = new TreeCache(client, "/log");
// 添加监听器
cache.getListenable().addListener(
(c, e) -> {
TreeCacheEvent.Type type = e.getType();
switch (type) {
case NODE_ADDED:
System.out.println("节点被创建");
break;
case NODE_UPDATED:
System.out.println("节点数据被修改");
break;
case NODE_REMOVED:
System.out.println("节点被删除");
break;
case CONNECTION_SUSPENDED:
System.out.println("连接被中断");
break;
case CONNECTION_RECONNECTED:
System.out.println("重新连接");
break;
}
}
);
// 开始监听
cache.start();
while (true) ;
}
// 关闭客户端
@After
public void closeClient() {
if (client != null) {
client.close();
}
}
}
zookeeper的客户端框架Curator,封装了Zookeeper的基本操作,并且还提供了一些高级特性
最新推荐文章于 2022-11-26 13:40:40 发布