本文介绍Zookeeper Java API的使用
zookeeper操作命令:
ls / 查找根目录
create /test abc 创建节点并赋值
get /test 获取指定节点的值
set /test cb 设置已存在节点的值
rmr /test 递归删除节点
delete /test/test01 删除不存在子节点的节点
maven构建的项目,加入以下依赖
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>3.4.10</version>
</dependency>
1、连接
String connectionString = "127.0.0.1:2181";
int sessionTimeout = 30000;
ZooKeeper zk = new ZooKeeper(connectionString,sessionTimeout,null
});
connectionString是连接信息,当为集群的时候,使用”,”分隔,如
“192.168.1.1:2181,192.168.1.2:2181”
sessionTimeout指会话过期时间,其值minSessionTimeout最小为tickTime的2倍,最大值 maxSessionTimeout为tickTime的20倍;即使传入的值不在此范围实际起作用的也是minSessionTimeout至maxSessionTimeout
2、创建节点
zk.create("/testRoot","testRoot".getBytes(),
ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT);
类型 描述
CreateMode.PERSISTENT 永久性节点
CreateMode.PERSISTENT_SEQUENTIAL 永久性序列节点
CreateMode.EPHEMERAL 临时节点,会话断开或过期时会删除此节点
CreateMode.PERSISTENT_SEQUENTIAL 临时序列节点,会话断开或过期时会删除此节点
3、获取节点
Stat stat = new Stat();
zk.getData("/testRoot",true,stat);
4、修改节点数据
// -1表示忽略版本
zk.setData("/testRoot", "testRoot_modified".getBytes(), -1);
5、创建子节点
zk.create("/testRoot/child1","child1_data".getBytes(),
ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT);
6、获取子节点
List<String> children = zk.getChildren("/testRoot",new Watcher()
{
public void process(WatchedEvent event)
{
System.out.println("this is children node event");
System.out.println(event);
}
});
注:getChildren方法会在子点有变化时触发Watcher()这个监听器
7、删除节点
zk.delete("/testRoot", -1);
zk.delete("/testRoot/child1", -1);
8、关闭连连接
zk.close();
注:一般情况下close()方法放在finally代码块执行
关于KeeperErrorCode = ConnectionLoss错误
在使用Zookeeper API时,常常会引发以下错误 ,这是由于连接还未完成就执行zookeeper的get/create/exists操作引起的
完整案例
package com.liu.zookeeper;
import org.apache.zookeeper.*;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
/**
* @Author : ld
* @Description :
* @ClassName : Demo2API
* @Date : 2021/9/24 19:06
* @Version : 1.0
*/
public class Demo2API {
ZooKeeper zk;
@Before
public void init(){
try {
zk = new ZooKeeper("master:2181,slave1:2181,slave2:2181", 3000, null);
} catch (IOException e) {
e.printStackTrace();
}
}
// CreateMode.EPHEMERAL 临时的
//PERSISTENT 永久的
@Test
public void create(){
try {
zk.create("/test","test".getBytes(),
ZooDefs.Ids.OPEN_ACL_UNSAFE,
CreateMode.PERSISTENT);
} catch (KeeperException | InterruptedException e) {
e.printStackTrace();
}
try{
Thread.sleep(10000);
}catch (InterruptedException e){
e.printStackTrace();
}
}
//手动创建监听
@Test
public void watcher(){
try {
// 用来做绑定
zk.getChildren("/test", watchedEvent -> {
System.out.println("节点状态发生改变");
System.out.println(watchedEvent);
}
);
} catch (KeeperException | InterruptedException e) {
e.printStackTrace();
}
while (true){}
}
}