监控mq脚本

报警脚本

import requests
import json
import time
import sys
from requests.auth import HTTPBasicAuth

def formatMessage(queue_name,queue_count):
    message = u"HOST: mq.mq.com  %s 队列名称: %s  队列堆积: %s" % (time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())), queue_name, queue_count)
    String_textMsg = {
        "msgtype": "text",
        "text": {"content": message},
        "at": {
            "atMobiles": [
                "18600000000",
                "15700000000",
                "18200000000" # 如果需要@某人,这里写他的手机号
            ],
            "isAtAll": False  # 如果需要@所有人,这些写1
        }
    }
    String_textMsg = json.dumps(String_textMsg)
    return String_textMsg

def connErrFormatMessage():
   message = u"测试信息: HOST: mq.mq.com %s 服务状态异常" % (time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))
   String_textMsg = {
        "msgtype": "text",
        "text": {"content": message},
        "at": {
            "atMobiles": [
                "18600000000",
                "15700000000",
                "18200000000" # 如果需要@某人,这里写他的手机号
            ],
            "isAtAll": False  # 如果需要@所有人,这些写1
        }
    }
   String_textMsg = json.dumps(String_textMsg)
   return String_textMsg

def queueHandle():
    url = "https://oapi.dingtalk.com/robot/send?access_token=5031e8a158a429ad2494581b16000000000000b869043cd5904a9b74ddf"
    HEADERS = {
        "Content-Type": "application/json"
    }
    queue_url = "http://mq.mq.com:15672/api/queues"
    username = "admin"
    password = "1234@5678"
    queueCount = 200     # 队列堆积大于200报警
    res = requests.get(url=queue_url,auth=HTTPBasicAuth(username=username,password=password))
    if res.status_code != 200:
        message = connErrFormatMessage()
        requests.post(url, data=data, headers=HEADERS)
        return
    queues = json.loads(res.text)
    for queue in queues:
        # 获取每个队列的长度
        print("queue:>>>>", queue["name"],queue["messages"])
        queue_count = queue["messages"]
        print(queue_count)
        # 如果队列长度大于设定值则推送钉钉消息
        if queue_count > queueCount:
            # 往钉钉发送消息
            data = formatMessage(queue['name'],queue_count)
            requests.post(url, data=data, headers=HEADERS)

if __name__=="__main__":
    queueHandle()

报警内容

启动

/usr/bin/python3 /opt/monitor_rabbitmq.py

posted @ 2023-03-15 10:37  六月OvO  阅读(37)  评论(0编辑  收藏  举报