階段1:開發一個守護進程腳本每30秒實現檢測一次。mysql
階段2:若是同步出現以下錯誤號(1158,1159,1008,1007,1062),請跳過錯誤sql
階段3:請使用數組技術實現上述腳本(獲取主從判斷及錯誤號部分)數組
[root@slave ~]# mysql -u root -proot -e "show slave status\G;" *************************** 1. row *************************** Slave_IO_State: Waiting for master to send event Master_Host: 172.16.1.2 #當前的mysql master服務器主機 Master_User: myslave Master_Port: 3306 Connect_Retry: 60 Master_Log_File: master-bin.000003 Read_Master_Log_Pos: 471 Relay_Log_File: relay-log-bin.000002 Relay_Log_Pos: 252 Relay_Master_Log_File: master-bin.000003 Slave_IO_Running: Yes Slave_SQL_Running: Yes Master_SSL_Key: Seconds_Behind_Master: 0 #和主庫比同步延遲的秒數
準備: egrep "_Running|Behind_Master" slave.log #過濾 Slave_IO_Running: Yes Slave_SQL_Running: Yes Seconds_Behind_Master: 0 [root@slave ~]# egrep "_Running|Behind_Master" slave.log | awk '{print $NF}' Yes Yes 0
階段一:開發一個守護進程腳本每30秒實現檢測一次。bash
#!/bin/bash while true do array=($(egrep "_Running|Behind_Master" slave.log|awk '{print $NF}')) if [ "${array[0]}" == "Yes" -a "${array[1]}" == "Yes" -a "${array[2]}" == "0" ] then echo "MySQL is slave is ok" else char="MySQL slave is not ok" echo "$char" echo "$char"|mail -s "$char" 995345781@qq.com break fi sleep 30 done 執行結果: [root@slave ~]# sh test.sh MySQL is slave is ok MySQL is slave is ok
終極版:服務器
#!/bin/bash #Date:2017-7-3 #Author:xcn(baishuchao@yeah.net) #version 1.0 mysql_cmd="mysql -u root -proot" errorno=(1158 1159 1008 1007 1062) while true do array=($($mysql_cmd -e "show slave status\G"|egrep '_Running|Behind_Master|Last_SQL_Errno'|awk '{print $NF}')) if [ "${array[0]}" == "Yes" -a "${array[1]}" == "Yes" -a "${array[2]}" == "0" ] then echo "MySQL is slave is ok" else for ((i=0;i<${#errorno[*]};i++)) do if [ "${array[3]}" = "${errorno[$i]}" ];then $mysql_cmd -e "stop slave &&set global sql_slave_skip_counter=1;start slave;" fi done char="MySQL slave is not ok" echo "$char" echo "$char"|mail -s "$char" 995345781@qq.com break fi sleep 30 done
提示:這個腳本能夠用於生產環境中,監控mysql主從同步狀態是否異常,根據運維
'_Running|Behind_Master|Last_SQL_Errno'
這個進行判斷,若是不正常的話則會進一步判斷狀態碼,而後進行輸出,則會發郵件或短信給運維人員ide