MySQL + Keepalived 双主热备搭建( 七 )

}function service_error {echo -e "`date "+%F%H:%M:%S"`-----mysql service error,now stop keepalived-----" >> $mysql_errecho -e "n@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@n" >> $mysql_err}function query_error {echo -e "`date "+%F%H:%M:%S"`-----query error, but mysql service ok, retry after 30s-----" >> $mysql_errsleep 30excute_queryif [ $? -ne 0 ];thenecho -e "`date "+%F%H:%M:%S"`-----still can't execute query-----" >> $mysql_errecho -e "`date "+%F%H:%M:%S"`-----set read_only = 1 on DB1-----" >> $mysql_err$mysql_con -e "set global read_only = 1;" 2>> $mysql_errecho -e "`date "+%F%H:%M:%S"`-----kill current client thread-----" >> $mysql_errrm -f $mysql_kill_session &>/dev/null$mysql_con -NB -e 'select concat("kill ",id,";") frominformation_schema.PROCESSLIST where command="Query" or command="Execute"' > $mysql_kill_session$mysql_con -e "source $mysql_kill_session"sleep 2 echo -e "`date "+%F%H:%M:%S"`-----stop keepalived-----" >> $mysql_errsystemctl stop keepalived &>> $mysql_errecho -e "n@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@n" >> $mysql_errelseecho -e "`date "+%F%H:%M:%S"`-----query ok after 30s-----" >> $mysql_errecho -e "n@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@n" >> $mysql_errfi}excute_queryif [ $? -ne 0 ];thensystemctl status mysql &>/dev/nullif [ $? -ne 0 ];thenservice_errorelsequery_errorfifi
复制代码 
给检查脚本赋与执行权限:
 
chmod u+x /etc/keepalived/check_mysql.sh
复制代码主库 B 配置 Keepalived主库 B keepalived 配置文件,编辑 /etc/keepalived/keepalived.conf 文件:
 
global_defs { router_id keep_mysql_repl_g1# 负载均衡标识,在局域网内应该是唯一的 }# vrrp_instancevrrp_instance v_mysql_1 {state BACKUP# 指定该 keepalived 节点的初始状态(MASTER|BACKUP)interface ens192# VRRP 实例绑定的网口,用于发送 VRRP 包virtual_router_id 200# 路由ID,范围是0-255,主备都一样priority 90# 指定优先级,优先级高的将成为 MASTERadvert_int 1# 指定发送VRRP广播的间隔 。单位是秒nopreempt# 设置为不抢占 。默认是抢占的authentication {# 身份验证auth_type PASS# 指定认证方式auth_pass mysql# 指定认证所使用的密码 mysql,主备都一样}notify_master /etc/keepalived/notify_master_mysql.sh# 转换成 master 时,执行的脚本virtual_ipaddress { 192.168.1.38/24 } }
复制代码 
主库 B 脚本,当发生主从切换时,会执行该脚本 。编辑 /etc/keepalived/notify_master_mysql.sh 文件:
 
#!/bin/bash#/etc/keepalived/notify_master_mysql.sh#chmod u+x /etc/keepalived/notify_master_mysql.sh


推荐阅读