插件窝 干货文章 Centos7 mysql守护(定时检测mysql运行状态)

Centos7 mysql守护(定时检测mysql运行状态)

MySQL monitor systemctl bash 75    来源:    2025-05-11

CentOS 7 MySQL守护脚本(定时检测MySQL运行状态)

在CentOS 7上,你可以创建一个守护脚本来定时检测MySQL的运行状态,并在服务停止时自动重启它。以下是完整的实现方案:

方法一:使用Shell脚本和crontab

1. 创建MySQL监控脚本

sudo vi /usr/local/bin/mysql_monitor.sh

内容如下:

#!/bin/bash

# MySQL服务名称(根据你的实际安装方式调整)
MYSQL_SERVICE="mysqld"  # 也可能是mysql或mariadb

# 检查MySQL是否运行
if ! systemctl is-active --quiet $MYSQL_SERVICE; then
    # 记录日志
    echo "$(date '+%Y-%m-%d %H:%M:%S') - MySQL is not running, attempting to restart..." >> /var/log/mysql_monitor.log

    # 尝试重启MySQL
    systemctl restart $MYSQL_SERVICE

    # 检查重启是否成功
    if systemctl is-active --quiet $MYSQL_SERVICE; then
        echo "$(date '+%Y-%m-%d %H:%M:%S') - MySQL restarted successfully" >> /var/log/mysql_monitor.log
    else
        echo "$(date '+%Y-%m-%d %H:%M:%S') - Failed to restart MySQL" >> /var/log/mysql_monitor.log
    fi
fi

2. 设置脚本权限

sudo chmod +x /usr/local/bin/mysql_monitor.sh

3. 添加crontab任务

sudo crontab -e

添加以下内容(每5分钟检查一次):

*/5 * * * * /usr/local/bin/mysql_monitor.sh

方法二:使用systemd服务单元(推荐)

1. 创建监控服务单元文件

sudo vi /etc/systemd/system/mysql-monitor.service

内容如下:

[Unit]
Description=MySQL Monitor Service
After=network.target

[Service]
Type=simple
ExecStart=/usr/local/bin/mysql_monitor.sh
Restart=always
RestartSec=60s
User=root

[Install]
WantedBy=multi-user.target

2. 创建定时器单元文件

sudo vi /etc/systemd/system/mysql-monitor.timer

内容如下:

[Unit]
Description=Run MySQL monitor every 5 minutes

[Timer]
OnBootSec=5min
OnUnitActiveSec=5min

[Install]
WantedBy=timers.target

3. 启用并启动服务

sudo systemctl daemon-reload
sudo systemctl enable mysql-monitor.timer
sudo systemctl start mysql-monitor.timer

方法三:使用Monit监控工具

如果你需要更强大的监控功能,可以安装Monit:

1. 安装Monit

sudo yum install epel-release
sudo yum install monit

2. 配置Monit监控MySQL

编辑Monit配置文件:

sudo vi /etc/monit.d/mysql

添加以下内容:

check process mysqld with pidfile /var/run/mysqld/mysqld.pid
    start program = "/usr/bin/systemctl start mysqld"
    stop program = "/usr/bin/systemctl stop mysqld"
    if failed host 127.0.0.1 port 3306 protocol mysql then restart
    if 5 restarts within 5 cycles then timeout

3. 启动Monit服务

sudo systemctl enable monit
sudo systemctl start monit

验证方法

  1. 查看监控日志:

    tail -f /var/log/mysql_monitor.log
    
  2. 手动停止MySQL测试监控是否有效:

    sudo systemctl stop mysqld
    
  3. 检查MySQL是否被自动重启:

    systemctl status mysqld
    

以上方法中,方法一最简单直接,方法二更符合systemd管理方式,方法三功能最强大但配置稍复杂。你可以根据实际需求选择最适合的方案。