1. 使用Zookeeper自带命令行工具监控
Zookeeper自带的命令行工具可直接检查节点状态、连接情况和基本运行信息,适合快速排查问题。
/path/to/zookeeper/bin/zkServer.sh status,输出会显示节点角色(Leader/Follower/Standby)及运行状态。/path/to/zookeeper/bin/zkCli.sh -server <host>:<port>连接到集群,常用命令包括:
stat:查看当前节点的连接数、延迟、Znode数量等基本信息;cons:列出所有活跃连接及操作统计;ruok:检查节点是否存活(返回“imok”表示正常)。/path/to/zookeeper/logs/zookeeper.out,使用tail -f实时跟踪日志,可快速定位错误或异常。2. 使用系统工具监控资源使用
通过Linux系统工具监控Zookeeper进程的CPU、内存、磁盘和网络资源,及时发现资源瓶颈。
top -p $(cat /path/to/zookeeper/data/myid)(需替换为实际myid文件路径)查看Zookeeper进程的CPU和内存使用率。ss -tuln | grep 2181(默认端口2181)检查Zookeeper端口是否正常监听,确保客户端可连接。iostat -x 1查看磁盘IO负载,避免因磁盘性能不足导致Zookeeper延迟升高。3. 基于JMX的监控(适合深度指标分析)
JMX可提供Zookeeper的详细运行指标(如请求延迟、连接数、Znode数量等),需配合可视化工具(如JConsole、VisualVM)使用。
zkServer.sh),添加JMX参数:export JVMFLAGS="-Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=9999 -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false"
jconsole命令),选择“远程进程”,输入<hostname>:9999即可查看各项指标(如AvgLatency、PacketsReceived、OutstandingRequestsCount)。4. 使用Telegraf+Prometheus+Grafana监控(自动化、可视化方案)
此方案适合大规模集群,实现自动化指标收集、存储和可视化。
sudo apt update && sudo apt install telegraf安装Telegraf。/etc/telegraf/telegraf.conf,添加inputs.zookeeper插件:[[inputs.zookeeper]]
interval = "60s"
servers = ["localhost:2181"] # 替换为Zookeeper节点地址
timeout = "5s"
sudo systemctl restart telegraf使配置生效。wget https://github.com/prometheus/prometheus/releases/download/v2.30.3/prometheus-2.30.3.linux-amd64.tar.gz),编辑prometheus.yml添加Zookeeper抓取任务:scrape_configs:
- job_name: 'zookeeper'
static_configs:
- targets: ['localhost:9143'] # Telegraf默认暴露端口
sudo apt install grafana安装Grafana,访问http://<ip>:3000(默认账号admin/admin),添加Prometheus数据源,导入Zookeeper监控面板(如ID:1860,社区提供的预置面板)。5. 使用Zookeeper Exporter+Prometheus+Grafana监控(轻量级方案)
Zookeeper Exporter是专门为Zookeeper设计的轻量级指标收集工具,适合不想使用Telegraf的场景。
wget https://github.com/carlpett/zookeeper_exporter/releases/download/v1.0.2/zookeeper_exporter-1.0.2.linux-amd64.tar.gz),解压后执行./zookeeper_exporter -config.file=zookeeper_exporter.yml(默认监听9143端口)。prometheus.yml中添加任务:scrape_configs:
- job_name: 'zookeeper_exporter'
static_configs:
- targets: ['localhost:9143']
6. 自定义脚本监控(定制化需求)
若需要特定指标的警报(如节点宕机、Znode数量超过阈值),可编写Shell或Python脚本,定期检查状态并通过邮件/Slack发送警报。
#!/bin/bash
STATUS=$(/path/to/zookeeper/bin/zkServer.sh status)
if echo "$STATUS" | grep -q "Leader"; then
echo "Zookeeper is Leader"
elif echo "$STATUS" | grep -q "Follower"; then
echo "Zookeeper is Follower"
else
echo "Zookeeper is down!" | mail -s "Zookeeper Alert" admin@example.com
fi
crontab -e,添加* * * * * /path/to/script.sh(每分钟执行一次)。