mysql从库宕机,再次启动之后,一直提示1062同步主键冲突,这个时候我们需要手动跳过在mysql的命令行中执行"set GLOBAL SQL_SLAVE_SKIP_COUNTER=1;",进行一次跳过。但是一般情况下需要执行很多次,以下用脚本检测1062主键冲突,然后自动跳过。
cat mysql_skip_1062.sh
#>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
## 如果同步的过程中,出现重复记录导致同步失败,就跳过
LOGFILE=log.mysql_skip_1062
SQLCMD1="show slave status"
user_password="-uroot -p123321"
while true
do
IO_STATUS=`mysql ${user_password} -e "${SQLCMD1}\G;" | awk '$1=="Slave_IO_Running:" {print $2}'`
SQL_STATUS=`mysql ${user_password} -e "${SQLCMD1}\G;" | awk '$1=="Slave_SQL_Running:" {print $2}'`
#BEHIND_STATUS=`mysql ${user_password} -e "${SQLCMD1}\G;" | awk '$1=="Seconds_Behind_Master:" {print $2}'`
#SLAVE_BINLOG1=`mysql ${user_password} -e "${SQLCMD1}\G;" | awk '$1=="Master_Log_File:" {print $2}'`
#SLAVE_BINLOG2=`mysql ${user_password} -e "${SQLCMD1}\G;" | awk '$1=="Relay_Master_Log_File:" {print $2}'`
ERROR_NUM=`mysql ${user_password} -e "${SQLCMD1}\G;" | awk '$1=="Last_Errno:" {print $2}'`
## 出现错误,就将错误信息记录到日志文件,并跳过错误继续同步
if [[ "${IO_STATUS}" != "Yes" || "${SQL_STATUS}" != "Yes" ]]; then
ERRORINFO=`mysql ${user_password} -e "${SQLCMD1}\G;" | awk '$1=="Last_Error:" {print $2_$3_$4_$5}'`
echo "${ERRORINFO}"
echo "${ERRORINFO}" >> ${LOGFILE}
if [[ "${ERROR_NUM}" == "1062" ]]; then
echo "do something for: ${ERROR_NUM}"
mysql ${user_password} -e "stop slave;"
mysql ${user_password} -e "set GLOBAL SQL_SLAVE_SKIP_COUNTER=1;"
mysql ${user_password} -e "start slave;"
fi
sleep 2
## 已完成同步,就正常退出
elif [[ "${IO_STATUS}" = "Yes" && "${SQL_STATUS}" = "Yes" && "${SLAVE_BINLOG1}" = "${SLAVE_BINLOG2}" && ${BEHIND_STATUS} -eq 0 ]]; then
echo The MySQL synchronous is ok at: `date +%F" "%H-%M-%S` >> ${LOGFILE}
break
fi
done
#<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<