本文共 2497 字,大约阅读时间需要 8 分钟。
企业面试题1:(生产实战案例):监控MySQL主从同步是否异常,如果异常,则发送短信或者邮件给管理员。提示:如果没主从同步环境,可以用下面文本放到文件里读取来模拟:阶段1:开发一个守护进程脚本每30秒实现检测一次。阶段2:如果同步出现如下错误号(1158,1159,1008,1007,1062),则跳过错误。阶段3:请使用数组技术实现上述脚本(获取主从判断及错误号部分)
此题来自:
解答参考1:
#!/bin/sh#oldboy linux training#2015-05-17#说明:本脚本来自老男孩linux21期学员张耀开发!# Source function library.. /etc/init.d/functions# Defined variablesMysqlUser=rootMysqlPass=oldboy123MysqlPort=3307Mysqlsock=/data/$MysqlPort/mysql.sockErrorNo=(1158 1159 1008 1007 1062)errorlog=/tmp/error_skip.logMysqlCmd="/application/mysql/bin/mysql -u$MysqlUser -p$MysqlPass -S $Mysqlsock"# Judge mysql server is ok?[ -S $Mysqlsock ] ||{ echo "Maybe MySQL have someting wrong" exit 1}# Defined skip error Functionsfunction error_skip(){ local flag flag=0 for num in ${ErrorNo[@]} do if [ "$1" == "$num" ];then $MysqlCmd -e'stop slave;set global sql_slave_skip_counter=1;start slave;' echo "$(date +%F_%R) $1" >>$errorlog else echo "$(date +%F_%R) $1" >>$errorlog ((flag++)) fi done [ "$flag" == "${#ErrorNo[@]}" ] &&{ action "MySQL Slave" /bin/false uniq $errorlog|mail -s "MySQL Slave is error" 12345678@qq.com }}# Defined check slave Functionsfunction check_slave(){ MyResult=`$MysqlCmd -e'show slave status\G'|egrep '_Running|Behind_Master|SQL_Errno' |awk '{print $NF}'` array=($MyResult) if [ "${array[0]}" == "Yes" -a "${array[1]}" == "Yes" -a "${array[2]}" == "0" ] then action "MySQL Slave" /bin/true else error_skip ${array[3]} fi}# Defined main Functionsfunction main(){ while true do check_slave sleep 60 done}main
解答参考2:
#!/bin/sh#oldboy linux#2015-05-17#说明:本脚本来自老男孩教育21期学员李新宇!USER=rootPASSWORD=123456PORT=3307error=(1158 1159 1008 1007 1062)MYSQLCMD="mysql -u$USER -p$PASSWORD -S /data/$PORT/mysql.sock"is_run(){ [ `lsof -i:$PORT|wc -l` -lt 2 ]&&{ echo "mysql server is stopped" exit 1 }}status_array(){ status=($($MYSQLCMD -e "show slave status\G"|egrep "_Running|Last_Errno|Behind_Master"|awk '{print $NF}'))}status_error(){for((i=0;i<${#error[*]};i++))do if [ "$1" == "${error[$i]}" ] then $MYSQLCMD -e "stop slave;set global sql_slave_skip_counter=1;start slave;" else echo "MySQL slave is failed, errorno is $1" fidone}judge_slave(){ status_array if [ "${status[0]}" == "Yes" -a "${status[1]}" == "Yes" -a "${status[3]}" = "0" ] then echo "MySQL slave is ok" else status_error ${status[2]} fi}main(){while truedo is_run judge_slave sleep 60done}main
老男孩老师提示:企业实际场景,还可能根据主库写时间戳的方式更严格的判断数据库是否同步。
转载地址:http://dqado.baihongyu.com/