在CentOS 7上,你可以创建一个守护脚本来定时检测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
sudo chmod +x /usr/local/bin/mysql_monitor.sh
sudo crontab -e
添加以下内容(每5分钟检查一次):
*/5 * * * * /usr/local/bin/mysql_monitor.sh
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
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
sudo systemctl daemon-reload
sudo systemctl enable mysql-monitor.timer
sudo systemctl start mysql-monitor.timer
如果你需要更强大的监控功能,可以安装Monit:
sudo yum install epel-release
sudo yum install monit
编辑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
sudo systemctl enable monit
sudo systemctl start monit
查看监控日志:
tail -f /var/log/mysql_monitor.log
手动停止MySQL测试监控是否有效:
sudo systemctl stop mysqld
检查MySQL是否被自动重启:
systemctl status mysqld
以上方法中,方法一最简单直接,方法二更符合systemd管理方式,方法三功能最强大但配置稍复杂。你可以根据实际需求选择最适合的方案。