本文目录导读:

是的,脚本可以自动监控 RabbitMQ 队列,常用的方法有以下几种:
使用 RabbitMQ 管理 API(HTTP)
import requests
import time
def check_queue():
url = "http://localhost:15672/api/queues/%2F/your_queue_name"
auth = ("username", "password")
response = requests.get(url, auth=auth)
data = response.json()
messages = data.get('messages', 0)
consumers = data.get('consumers', 0)
return messages, consumers
# 监控脚本
while True:
messages, consumers = check_queue()
print(f"队列消息数: {messages}, 消费者数: {consumers}")
if messages > 100:
print("警告:队列积压过高")
# 发送告警通知
if consumers == 0:
print("警告:队列没有消费者")
time.sleep(30) # 每30秒检查一次
使用命令行工具
#!/bin/bash
# 监控队列的Shell脚本
QUEUE="your_queue_name"
RABBITMQCTL="/usr/sbin/rabbitmqctl"
while true; do
# 获取队列状态
QUEUE_INFO=$($RABBITMQCTL list_queues name messages consumers | grep $QUEUE)
if [ -z "$QUEUE_INFO" ]; then
echo "警告:队列 $QUEUE 不存在"
else
MESSAGES=$(echo $QUEUE_INFO | awk '{print $2}')
CONSUMERS=$(echo $QUEUE_INFO | awk '{print $3}')
echo "队列: $QUEUE 消息数: $MESSAGES 消费者: $CONSUMERS"
fi
sleep 30
done
使用 Prometheus + Grafana 监控
RabbitMQ Exporter 配置示例:
# docker-compose.yml
services:
rabbitmq:
image: rabbitmq:3-management
ports:
- "15672:15672"
prometheus:
image: prom/prometheus
volumes:
- ./prometheus.yml:/etc/prometheus/prometheus.yml
grafana:
image: grafana/grafana
ports:
- "3000:3000"
使用 Python 告警脚本示例
import pika
import time
import smtplib
from datetime import datetime
def monitor_and_alert():
connection = pika.BlockingConnection(
pika.ConnectionParameters('localhost')
)
channel = connection.channel()
# 获取队列状态
queue = channel.queue_declare(
queue='your_queue',
passive=True,
durable=True
)
message_count = queue.method.message_count
consumer_count = queue.method.consumer_count
# 告警条件
if message_count > 500:
send_alert(f"队列消息积压: {message_count}")
elif message_count > 100:
send_warning(f"队列消息增加: {message_count}")
connection.close()
def send_alert(message):
print(f"[{datetime.now()}] 告警: {message}")
# 实际发送邮件或消息通知
# 定时运行
while True:
monitor_and_alert()
time.sleep(60) # 每60秒检查一次
使用监控工具
Nagios 监控脚本示例:
#!/bin/bash
# check_rabbitmq_queue.sh
QUEUE=$1
WARN_LEVEL=$2
CRIT_LEVEL=$3
# 获取队列状态
MESSAGES=$(curl -s -u guest:guest http://localhost:15672/api/queues/%2F/$QUEUE |
python -c "import sys,json; print(json.load(sys.stdin)['messages'])")
if [ $MESSAGES -ge $CRIT_LEVEL ]; then
echo "CRITICAL - 队列 $QUEUE 有 $MESSAGES 条消息"
exit 2
elif [ $MESSAGES -ge $WARN_LEVEL ]; then
echo "WARNING - 队列 $QUEUE 有 $MESSAGES 条消息"
exit 1
else
echo "OK - 队列 $QUEUE 有 $MESSAGES 条消息"
exit 0
fi
最佳实践建议
-
监控指标:
- 消息数量
- 消费者数量
- 消息处理延迟
- 队列深度
- 未确认消息数
-
告警策略:
- 队列积压超过阈值
- 消费者断开
- 消息无法投递
- 内存使用过高
-
部署方式:
- 作为系统服务运行
- 集成到 CI/CD 流水线
- 使用容器化部署
推荐使用 Prometheus + Grafana 组合进行生产环境监控,它提供了更完善的可视化和告警功能。