依赖
org.apache.zookeeper
zookeeper
3.6.0
连接到zkServer
//连接字符串,zkServer的ip、port,如果是集群逗号分隔
String connectStr = "192.168.1.9:2181";
//zookeeper就是一个zkCli
ZooKeeper zooKeeper = null;
try {
//初始次数为1。后面要在内部类中使用,三种写法:1、写成外部类成员变量,不用加final;2、作为函数局部变量,放在try外面,写成final;3、写在try中,不加final
CountDownLatch countDownLatch = new CountDownLatch(1);
//超时时间ms,监听器
zooKeeper = new ZooKeeper(connectStr, 5000, new Watcher() {
public void process(WatchedEvent watchedEvent) {
//如果状态变成已连接
if (watchedEvent.getState().equals(Event.KeeperState.SyncConnected)) {
System.out.println("连接成功");
//次数-1
countDownLatch.countDown();
}
}
});
//等待,次数为0时才会继续往下执行。等待监听器监听到连接成功,才能操作zk
countDownLatch.await();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
//...操作zk。后面的demo都是写在此处的
//关闭连接
try {
zooKeeper.close();
} catch (InterruptedException e) {
e.printStackTrace();
}
检测节点是否存在
// 检测节点是否存在
// 同步方式
Stat exists = null;
try {
//如果存在,返回节点状态Stat;如果不存在,返回null。第二个参数是watch
exists = zooKeeper.exists("/mall",false);
} catch (KeeperException | InterruptedException e) {
e.printStackTrace();
}
if (exists==null){
System.out.println("节点不存在");
}
else {
System.out.println("节点存在");
}
//异步回调
zooKeeper.exists("/mall",false, new AsyncCallback.StatCallback() {
//第二个是path znode路径,第三个是ctx 后面传入实参,第四个是znode的状态
public void processResult(int i, String s, Object o, Stat stat) {
//如果节点不存在,返回的stat是null
if (stat==null){
System.out.println("节点不存在");
}
else{
System.out.println("节点存在");
}
}
// 传入ctx,Object类型
},null);
操作后,服务端会返回处理结果,返回void、null也算处理结果。
同步指的是当前线程阻塞,等待服务端返回数据,收到返回的数据才继续往下执行;
异步回调指的是,把对结果(返回的数据)的处理写在回调函数中,当前线程不等待返回的数据,继续往下执行,收到返回的数据时自动调用回调函数来处理。
如果处理返回数据的代码之后的操作