zookeeper客户端读取子节点的信息

本文介绍如何使用ZooKeeper客户端监控特定路径下的任务状态,包括获取子节点列表及节点数据,并通过示例代码展示了如何实现这一过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在zookeeper目录下启动zookeeper客户端:./zkCli.sh(在bin目录下)

这里写图片描述

用 ls /命令来显示该节点下所有的子节点,get /MsgBusMonitor显示该节点下的所有详细信息。

这里写图片描述

Object[][] result = null;

//连接服务器的IP地址和端口号
String connectString = "10.0.0.100:2181";
//超时时间
int sessionTimeout = 5000;

try {
    zk = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
        @Override
        public void process(WatchedEvent event) {
            //不做操作
        }
    });
    // 获取任务实例example,task_schedule是子节点
    List<String> example = zk.getChildren("/task_schedule", true);
    List<String> list = null;
    int number = 0;int allCount = 0;
    for (int j = 0; j < example.size(); j++) {
        List<String> runNode = zk.getChildren("/task_schedule/" + example.get(j), true);
        boolean numberFlag = true;
        if (runNode != null || !runNode.equals("")) {// 节点存在的时候
            for (int i = 0; i < runNode.size(); i++) {
                number++;
                numberFlag = false;
            }
        }
        if(numberFlag==true){
            allCount++;
        }
    }
    result = new Object[number+allCount][3];
    int a = 0;
    for (int j = 0; j < example.size(); j++) {
        boolean flag = true;
        // 获取运行节点runNode
        List<String> runNode = zk.getChildren("/task_schedule/" + example.get(j), true);

        if (runNode != null || !runNode.equals("")) {// 节点存在的时候
            for (int i = 0; i < runNode.size(); i++) {
                byte[] data = zk.getData("/task_schedule/" + example.get(j) + "/" + runNode.get(i), null,
                        null);
                result[a][0] = example.get(j);
                result[a][1] = runNode.get(i);
                if(Character.isDigit(new String(data).charAt(0))){
                    result[a][2] = new String(data);
                }else{
                    result[a][2] = "任务获取失败";
                }

                a++;
                flag = false;
            }
        }
        if (flag == true) {
            result[a][0] = example.get(j);
            result[a][1] = "";
            result[a][2] = "";
            a++;
        }
    }
} catch (KeeperException e) {
    e.printStackTrace();
} catch (InterruptedException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值