Zookeeper概念
- 树形目录服务
- 分布式的、开源的分布式应用程序的协调服务
- 提供功能包括
- 配置管理
- 分布式锁
- 集群管理
ZooKeeper命令操作
数据模型
- 树形结构的每一个节点都被称为ZNode,每个节点上都会保存自己的数据和节点信息
- 节点可以拥有子节点,同时也允许少量数据存储在该节点之下
- 节点分为四大类
- PERSISTENT持久化节点
- EPHEMERAL临时节点:-e
- PERSISTENE_SEQUENTIAL持久化循序节点:-s
- EPHEMERAL_SEQUENTIAL临时顺序节点:-es
服务端常用命令
客户端常用命令
创建临时节点
create -e /节点path value
创建顺序节点
create -s /节点path value
查询节点详细信息
ls -s /节点path
Zookeeper JavaAPI操作
Curator介绍
是Zookeeper的Java客户端库
Curator常用操作
建立连接
添加节点
//如果创建节点没置顶数据,则默认将当前客户端ip存入
client.create().forPath("/app1","hehe".getBytes());
//默认类型:持久化
client.create().withMode(CreateMode.xxx).forPath("/app1");
//创建多级节点
client.create().creatingParentsIfNeeded().forPath("/app1/p1");
查询节点
//查询数据 get
byte[] data = client.getData().forPath("/app1");
//查询子节点 ls
byte[] data = client.getChildren().forPath("/app1");
//查询节点状态信息 -s
byte[] data = client.getData().storingStatIn().forPath("/app1");
修改节点
//修改数据
client.setData().forPath("/app1","xxx".getBytes());
//修改版本
client.setData().withVersion(version).forPath("/app1","xxx".getBytes());
删除节点
//删除单个
client.delete().forPath("/app1");
//删除有子节点的节点
client.delete().deletingChildrenIfNeeded().forPath("/app1");
//必须删除
client.delete().guaranteed().forPath("/app1");
//有回调
client.delete().guaranteed().inBackground(new BackgroundCallback(){
@Override
pubilc void processResult(...) {
...
}
}).forPath("/app1");
Watch事件监听
NodeCache
//1.创建NodeCache对象
NodeCache nodecache = new NodeCache(client,"path");
//2.注册监听
nodeCache.getListenable().addListener(new NodecacheListener() {
@Override
public void nodeChanged() throws Exception {
System.out.ptintln("节点xxx");
}
});
//3.开启监听
//true:开启监听时,加载缓冲数据
nodeCache.start(true);
PathChildrenCache
//1.创建PathChildrenCache对象
PathChildrenCache pathChildrenCache = new PathChildrenCache(xxx);
//2.注册监听
pathChildrenCache.getListenable().addListener(new PathChildrenCacheListener() {
@Override
public void chilEvent(xxx) throws Exception {
System.out.ptintln("节点xxx");
}
});
//3.开启监听
//true:开启监听时,加载缓冲数据
pathChildrenCache.start(true);
TreeCache
//1.创建PathChildrenCache对象
TreeCache treeCache = new TreeCache(client,"/app2");
//2.注册监听
TreeCache.getListenable().addListener(new TreeCacheListener() {
@Override
public void chilEvent(xxx) throws Exception {
System.out.ptintln("节点xxx");
}
});
//3.开启监听
//true:开启监听时,加载缓冲数据
treecache.start(true);
评论区
欢迎你留下宝贵的意见,昵称输入QQ号会显示QQ头像哦~