1、mysql主从监控的主要思路

Mysql主从的监控,其主要是监控从库上的一些重要参数:

Slave_IO_Running: Yes

Slave_SQL_Running: Yes

Master_Log_File: bin-log.003

Relay_Master_Log_File: bin-log.003

Read_Master_Log_Pos: 4

Exec_master_log_pos: 4

Seconds_Behind_Master: 0(5.0之前版本没有这个选项)

通过以上的参数可以反映出主库和从库状态是否正常,从库是否落后于主库等。值得一提的是在mysql5.0以前的版本,Slave_IO_Running这个状态指标不可靠,会在主库直接挂掉的情况下不会变成NO,Seconds_Behind_Master参数也不存在。监控以上参数即可监控mysql主从。

2、mysql主从监控的实现

不管mysql是那个版本,其中的从库上的Exec_master_log_pos、Exec_master_log_pos;主库上的 Master上的Log_File, Position,这四个参数可以判断出当前主从的状态。以下是适用于mysql所有版本的主从监控shell脚本:

#/bin/sh

user=repl

passwd=123415

master_ip="192.168.1.2"

log="/data3/check_repl.log"

value()

{

 master=`/usr/local/mysql/bin/mysql -u$user -p$passwd -h$master_ip -e "show master status\G;"|egrep "File|Position"`

 #mysql 4.0

 slave=`/usr/local/mysql/bin/mysql -u$user -p$passwd -h127.0.0.1 -e "show slave status\G;"|egrep "Relay_Master_Log_File|Exec_master_log_pos"`

 #mysql 5.0

 #slave=`mysql -u$user -p$passwd -e "show slave status\G;"|egrep "Relay_Master_Log_File|Exec_Master_Log_Pos"`

 #取主库上的bin-log号及写入的当前日志位置   

 Master_Log=`echo $master |awk '{print $2}'|awk -F "." '{print $2}'`

 Master_Log_Pos=`echo $master |awk '{print $4}'`

 #取从库上当前同步主库的位置

 Relay_Master_Log_File=`echo $slave |awk '{print $2}'|awk -F "." '{print $2}'`

 Exec_Master_Log_Pos=`echo $slave |awk '{print $4}'`

 echo "Master_Log:"$Master_Log>>$log

 echo "Master_Log_Pos:"$Master_Log_Pos>>$log

 echo "Relay_Master_Log_File:"$Relay_Master_Log_File>>$log

 echo "Exec_Master_Log_Pos:"$Exec_Master_Log_Pos>>$log

}

for((i=1;i<=10;i++));

do

 echo "#################################">>$log

 value

 time=`date +"%Y-%m-%d %H:%M:%S"`

 if [ $Master_Log -eq $Relay_Master_Log_File ];then

       A=`expr $Master_Log_Pos - $Exec_Master_Log_Pos`

       if [ $A -lt 0 ];then

             A=`expr 0 - $A`

       fi

       echo $A>>$log

       if [ $A -lt 10000 ];then

             echo "$time Master-Slave is OK.">>$log

             #echo "$i"

             break

       else

             if [ $i ge 3 ];then              

                  echo "$time Warning:Slave-Master lag $A " >>$log

                  echo "$i"

             fi

             sleep 30

             continue

       fi

 else

       sleep 60

       fi

       if [ $i -eq 10 ];then

             echo "$i"

             echo "$time Error:Slave-Master must be check !" >>$log

       fi

done

在mysql5.0以后的版本,mysql主从已经相当的成熟了,可以只监控Slave_IO_Running,Slave_SQL_Running,Seconds_Behind_Master状态就可以了