• ZkClient
• Curator
-
Curator 项目的目标是简化 ZooKeeper 客户端的使用。
-
Curator 最初是 Netfix 研发的,后来捐献了 Apache 基金会,目前是 Apache 的顶级项目。
package com.zk.test;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.api.BackgroundCallback;
import org.apache.curator.framework.api.CuratorEvent;
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;
public class CuratorTest {
CuratorFramework client;
//建立连接
@Before
public void testConnect(){
//第一种方式
/*
* zk地址和端口
* 会话超时时间 默认 60*1000
* 连接超时时间 默认 15*1000
* 重试策略
* */
RetryPolicy rp = new ExponentialBackoffRetry(3000,10);
// CuratorFramework client = CuratorFrameworkFactory.newClient("192.168.126.129:2181", rp);
// //开启连接
// client.start();
//第二种方式
client = CuratorFrameworkFactory.builder()
.connectString("192.168.126.129:2181")
.sessionTimeoutMs(60 * 1000)
.connectionTimeoutMs(15 * 1000)//namespace会让app1作为根目录
.retryPolicy(rp).namespace("app1").build();
//开启连接
client.start();
}
/*=================创建结点=======================*/
@Test
public void testCreate() throws Exception {
//如果没有指定数据,客户端ip会作为数据
String s = client.create().forPath("/app2","abc".getBytes());
System.out.println(s);
}
@Test
public void testCreate2() throws Exception {
//指定类型 默认:持久化
String s = client.create().withMode(CreateMode.EPHEMERAL).forPath("/app3","abc".getBytes());
System.out.println(s);
//延迟会话执行结束
int i=0;
while(i<20){
Thread.sleep(1000);
i++;
System.out.println(i);
}
}
@Test
public void testCreate3() throws Exception {
//创建多级结点
//creatingParentsIfNeeded():如果父节点不存在,则创建父节点
String s = client.create().creatingParentsIfNeeded().forPath("/app4/p1");
System.out.println(s);
}
/*=================查询结点=======================*/
//查询数据
@Test
public void get() throws Exception {
byte[] bytes = client.getData().forPath("/app2");
System.out.println(new String(bytes));
}
//查询结点
@Test
public void get2() throws Exception {
List<String> paths = client.getChildren().forPath("/app4");
System.out.println(paths);
}
//状态信息
@Test
public void get3() throws Exception {
Stat stat = new Stat();
client.getData().storingStatIn(stat).forPath("/app4");
System.out.println(stat);
}
/*=================修改结点=======================*/
//修改数据
@Test
public void set() throws Exception {
client.setData().forPath("/app2","aaa".getBytes());
}
//根据版本修改数据
@Test
public void set2() throws Exception {
Stat stat = new Stat();
client.getData().storingStatIn(stat).forPath("/app2");
int version = stat.getVersion();
System.out.println(version);
client.setData().withVersion(version).forPath("/app2","bbb".getBytes());
}
/*=================删除结点=======================*/
//删除单个结点
@Test
public void delete() throws Exception {
client.delete().forPath("/app2");
}
//删除带子结点的结点
@Test
public void delete2() throws Exception {
client.delete().deletingChildrenIfNeeded().forPath("/app4");
}
//必须删除
@Test
public void delete3() throws Exception {
client.delete().guaranteed().forPath("/app4");
}
//回调
@Test
public void delete4() throws Exception {
client.delete().inBackground(new BackgroundCallback() {
@Override
public void processResult(CuratorFramework curatorFramework, CuratorEvent curatorEvent) throws Exception {
System.out.println("已删除");
System.out.println(curatorEvent);
}
}).forPath("/app3");
}
@After
public void after(){
if(client != null){
client = null;
}
}
}
2、Watch事件监听
-
ZooKeeper 允许用户在指定节点上注册一些Watcher,并且在一些特定事件触发的时候,ZooKeeper 服务端会将事件通知到感兴趣的客户端上去,该机制是 ZooKeeper 实现分布式协调服务的重要特性。
-
ZooKeeper 中引入了Watcher机制来实现了发布/订阅功能能,能够让多个订阅者同时监听某一个对象,当一个对象自身状态变化时,会通知所有订阅者。
-
Curator引入了 Cache 来实现对 ZooKeeper 服务端事件的监听。
-
ZooKeeper提供了三种Watcher:
• NodeCache : 只是监听某一个特定的 节点
• PathChildrenCache : 监控一个 ZNode 的子节点 .
• TreeCache : 可以监控整个树上的所有节点, 类似于 PathChildrenCache 和 NodeCache 的组合
@Test
public void testNodeCache() throws Exception {
//创建NodeCache对象
final NodeCache nc = new NodeCache(client,"/app1");
//注册监听
nc.getListenable().addListener(new NodeCacheListener() {
@Override
public void nodeChanged() throws Exception {
System.out.println("结点变化了。。。");
//获取修改结点后的数据
byte[] data = nc.getCurrentData().getData();
System.out.println(new String(data));
}
});
//开启监听
nc.start(true);
while (true){
}
}
@Test
public void testPathChildrenCache() throws Exception {
final PathChildrenCache pcc = new PathChildrenCache(client,"/app1",true);
pcc.getListenable().addListener(new PathChildrenCacheListener() {
@Override
public void childEvent(CuratorFramework curatorFramework, PathChildrenCacheEvent pathChildrenCacheEvent) throws Exception {
System.out.println("子结点变化了。。。");
System.out.println(pathChildrenCacheEvent);
//监听子结点数据变更
//获取类型
PathChildrenCacheEvent.Type type = pathChildrenCacheEvent.getType();
//判断是否为update
if(type.equals(PathChildrenCacheEvent.Type.CHILD_UPDATED)){
System.out.println("数据变了");
byte[] data = pathChildrenCacheEvent.getData().getData();
System.out.println(new String(data));
}
}
});
pcc.start();
while (true){
}
}
@Test
public void test() throws Exception {
TreeCache tc = new TreeCache(client,"/app");
tc.getListenable().addListener(new TreeCacheListener() {
@Override
public void childEvent(CuratorFramework curatorFramework, TreeCacheEvent treeCacheEvent) throws Exception {
System.out.println("结点变化了。。。");
System.out.println(treeCacheEvent);
}
});
tc.start();
while(true){
}
}
3、分布式锁
最后
本人也收藏了一份Java面试核心知识点来应付面试,借着这次机会可以免费送给我的读者朋友们
目录:
Java面试核心知识点
一共有30个专题,足够读者朋友们应付面试啦,也节省朋友们去到处搜刮资料自己整理的时间!有需要的朋友戳这里即可免费获取
Java面试核心知识点
已经有读者朋友靠着这一份Java面试知识点指导拿到不错的offer了,各位读者朋友们快来免费获取吧
}
});
tc.start();
while(true){
}
}
### 3、分布式锁
# 最后
本人也收藏了一份Java面试核心知识点来应付面试,借着这次机会可以免费送给我的读者朋友们
**目录:**
[外链图片转存中...(img-P17PAYQB-1628360458795)]
Java面试核心知识点
**一共有30个专题,足够读者朋友们应付面试啦,也节省朋友们去到处搜刮资料自己整理的时间![有需要的朋友戳这里即可免费获取](https://gitee.com/vip204888/java-p7)**
[外链图片转存中...(img-dAWUa7tG-1628360458796)]
Java面试核心知识点
**已经有读者朋友靠着这一份Java面试知识点指导拿到不错的offer了,各位读者朋友们快来免费获取吧**
[外链图片转存中...(img-t6qWAjoE-1628360458798)]