很多时候,我们的mysql数据库会出现异常,崩溃,锁表,从而导致网站无法访问,根据下面的方法可以很方便地找出到底是什么引起Mysql出问题。

1.启用mysql慢日志查询
vi /etc/mysql/my.cnf
long_query_time = 2
log_slow_queries        = /var/log/mysql/mysql-slow.log

2.分析慢日志文件
cat /var/log/mysql/mysql-slow.log

3.查看Mysql进程
mysql -h localhost -uroot –pgaojinbo.com \
-e "show full processlist" 

4.编写shell脚本,kill异常的sql语句
vi dbkiller.sh
#!/bin/sh
process=`mysql -hlocalhost -uroot -pgaojinbo.com \
-e "show full processlist"|grep \
dbname_gaojinbo|grep Query|grep SELECT|\
grep "p.message LIKE"`
if [ ! "$process" = "" ]; then
process_id=`echo $process|awk {'print $1'}`
mysql -hlocalhost -uroot -pgaojinbo.com -e \
 "kill $process_id"
date=`date +"%Y-%m-%d %H:%M:%S"`
echo $date"     "$process >> \
/home/gaojinbo.com/dbkiller.log
fi

5.定时检测,每分钟执行1次
crontab -e
*/1 * * * * /home/gaojinbo.com/dbkiller.sh

完成!