Java中初始化zookeeper
使用springboot
- Idea新建springboot项目
- 导入额外的包:
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>3.5.3-beta</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
</dependency>
- 创建一个类zk:
编写初始化以及创建代码:
public class zk {
//注意逗号左右不能有空格
private String connectString = "192.168.59.128:2181,192.168.59.129:2181,192.168.59.130:2181"; //zookeeper客户端域名+端口号
private int sessionTimeout = 2000; //超时时间
ZooKeeper zooKeeper;
@Before //初始化连接
public void init() throws IOException {
zooKeeper =new ZooKeeper(connectString, sessionTimeout, new Watcher() {
@Override
public void process(WatchedEvent watchedEvent) {
}
});
}
@Test //新建
public void create() throws KeeperException,InterruptedException{
String s = zooKeeper.create("/flyyant", "ss.avi".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); //创建flyyant节点,值为ss.avi,持久型
}
}
测试:
进入服务器的zookeeper客户端查看:
获取子节点并监听节点变化
编写代码:
@Test
public void getChildren() throws KeeperException,InterruptedException{
List<String> children = zooKeeper.getChildren("/", true); //监听根目录的变化
for (String child:children){
System.out.println(child);
}
}
测试:
在服务器内添加一个子节点:
程序因为已经结束运行而无法实时显示,原因是注册一次监听一次。优化:
添加延时:
在init的process中编写重复监听的内容:
测试:
客户端修改:
查看日志:
判断节点是否存在
先查看是否存在:
发现是存在的
编码:
@Test
public void exist() throws KeeperException,InterruptedException{
Stat stat = zooKeeper.exists("/flyyant", false);
System.out.println(stat==null?"not exist":"exist");
}
测试:
接下来删除一下试试看:
测试:
最近在学习zookeeper,有兴趣的小伙伴可以一起交流学习经验,欢迎留言