MySQL + Keepalived

Keepalived+mysql 自动切换

项目环境:

VIP 192.168.14.110
mysql1 192.168.14.120
mysql2 192.168.14.130

实施步骤

一. keepalived 主备配置文件

192.168.14.120 Master配置

[root@localhost ~]# vim /etc/keepalived/keepalived.conf
==============================================================
! Configuration File for keepalived

global_defs {
    router_id mysqli
}

vrrp_script check_run {
    script "/root/keepalived_check_mysql.sh"
    interval 5
}

vrrp_instance VI_1 {
    state MASTER
    interface ens33
    virtual_router_id 88
    priority 100
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass 1111
    }

    track_script {
        check_run
    }

    virtual_ipaddress {
        192.168.14.100
    }
}

192.168.14.130 Master配置

[root@localhost ~]# vim /etc/keepalived/keepalived.conf
==============================================================
! Configuration File for keepalived

global_defs {
    router_id mysql2
}

vrrp_script check_run {
    script "/root/keepalived_check_mysql.sh"
    interval 5
}

vrrp_instance VI_1 {
    state BACKUP
    interface ens33
    virtual_router_id 88
    priority 50
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass 1111
    }

    track_script {
        check_run
    }

    virtual_ipaddress {
        192.168.14.100
    }
}

1.注意空格

2.日志查看脚本是否执行

[root@localhost ~]# tailf /var/log/messages
Jun 19 15:20:19 xen1 Keepalived_vrrp[6341]: Using LinkWatch kernel netlink reflector...
Jun 19 15:20:19 xen1 Keepalived_vrrp[6341]: VRRP sockpool: [ifindex(2),proto(112),fd(11,12)]
Jun 19 15:20:19 xen1 Keepalived_vrrp[6341]: VRRP_Script(check_run) succeeded

二.mysql状态检查脚本/root/keepalived_check_mysql.sh (两台mysql同洋的脚本)

版本一:简单实用

#!/bin/bash
/usr/bin/mysql -uroot -p123456 -e "show status" &>/dev/null
if [ $? -ne 0 ] ;then
    service keepalived stop
fi

版本二: 检查多次

[root@localhost ~]# vim /root/keepalived_check_mysql.sh
========================================================
#!/bin/bash
MYSQL=/usr/local/mysql/bin/mysql
MYSQL_HOST=localhost
MYSQL_USER=root
MYSQL_PASSWORD=123456
CHECK_TIME=3

#mysql is working MYSQL_OK is 1 , mysql down MYSQL_OK is 0
MYSQL_OK=1

check_mysql_health (){
    $MYSQL -h $MYSQL_HOST -u $MYSQL_USER -p${MYSQL_PASSWORD} -e "show status" &>/dev/null
    if [ $? -eq 0 ] ;then
        MYSQL_OK=1
    else
        MYSQL_OK=0
    fi
    return $MYSQL_OK
}

while [$CHECK_TIME -ne 0 ]
do
    check_mysql_health
    if [ $MYSQL_OK -eq 1 ] ; then
        exit 0
    fi

    if [ $MYSQL_OK -eq 0 ] && [ $CHECK_TIME -eq 1 ] ; then
        /etc/init.d/keepalived stop
        exit 1
    fi
    let CHECK_TIME--
    sleep 1
done

主备都启动

[root@localhost ~]# chmod 744 /root/keepalived_check_mysql.sh
[root@localhost ~]# /etc/init.d/keepalived start
[root@localhost ~]# chkconfig --add keepalived
[root@localhost ~]# chkconfig keepalived on