代码示例
package learn.zk.base;
import org.apache.zookeeper.AsyncCallback;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import java.util.List;
import java.util.concurrent.CountDownLatch;
/**
* @PackageName : learn.zk.base
* @ClassName : Zk_GetChildren_API_ASync
* @Author : LingYi
* @Date : 2021/1/26 20:32
* @Description : 使用异步API获取子节点列表
*/
public class Zk_GetChildren_API_ASync implements Watcher {
/**
* zookeeper地址
*/
static final String CONNECT_ADDR = "192.168.31.207:2181,192.168.31.244:2181,192.168.31.212:2181";
/**
* session超时时间
*/
static final int SESSION_OUT_TIME = 4000;//ms
/**
* 信号量,阻塞程序执行,用于等待zookeeper连接成功,发送成功信号
*/
static final CountDownLatch connectedSemaphore = new CountDownLatch(1);
public static void main(String[] args) throws Exception {
ZooKeeper zk = new ZooKeeper(CONNECT_ADDR, SESSION_OUT_TIME, new Zk_GetChildren_API_ASync());
connectedSemaphore.await();
System.out.println("......");
/**
* path: 路径
* watch:是否注册watch
* ZkChildrenASync:回调方法
* Object:传递一个上下文
**/
zk.getChildren("/", true, new ZkChildrenASync(), "Context");
zk.close();
}
@Override
public void process(WatchedEvent event) {
if (Event.KeeperState.SyncConnected == event.getState() && Event.EventType.None == event.getType()) {
//如果建立连接成功,则发送信号量,让后续阻塞程序向下执行
connectedSemaphore.countDown();
System.out.println("zk 建立连接");
}
}
}
/**
* @PackageName : learn.zk.base
* @ClassName : ZkChildrenASync
* @Description : 异步回调
*/
class ZkChildrenASync implements AsyncCallback.Children2Callback {
@Override
public void processResult(int rc, String path, Object ctx, List<String> children, Stat stat) {
System.out.println("rc:" + rc + ",path:" + path + ",ctx:" + ctx.toString() + ",children:" + children + ",stat:" + stat);
}
}
执行结果: