记录日常工作关于系统运维,虚拟化云计算,数据库,网络安全等各方面问题。


以下内容是AI生成,不保证正常能用:


使用keepalived实现MySQL主从模式自动切换数据库的步骤如下:


1. 安装keepalived


在主库和从库上安装keepalived:


```bash
yum install keepalived -y
```


2. 配置keepalived


在主库和从库上分别创建/etc/keepalived/keepalived.conf文件,内容如下:


主库:


```bash
global_defs {
   router_id mysql_master
}


vrrp_script chk_mysql {
   script "/etc/keepalived/check_mysql.sh"
   interval 2
   weight -2
}


vrrp_instance VI_1 {
    state MASTER
    interface eth0
    virtual_router_id 51
    priority 101
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass 1111
    }
    virtual_ipaddress {
        192.168.1.100
    }
    track_script {
        chk_mysql
    }
}
```


从库:


```bash
global_defs {
   router_id mysql_slave
}


vrrp_script chk_mysql {
   script "/etc/keepalived/check_mysql.sh"
   interval 2
   weight -2
}


vrrp_instance VI_1 {
    state BACKUP
    interface eth0
    virtual_router_id 51
    priority 100
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass 1111
    }
    virtual_ipaddress {
        192.168.1.100
    }
    track_script {
        chk_mysql
    }
}
```


其中,check_mysql.sh脚本用于检测MySQL主从复制状态,内容如下:


```bash
#!/bin/bash


MYSQL_USER="root"
MYSQL_PASSWORD="password"
MYSQL_HOST="localhost"
MYSQL_PORT="3306"


MYSQL_CMD="mysql -u${MYSQL_USER} -p${MYSQL_PASSWORD} -h${MYSQL_HOST} -P${MYSQL_PORT} -e"


MASTER_STATUS=`${MYSQL_CMD} "show master status\G" | grep -c "File:"`
SLAVE_STATUS=`${MYSQL_CMD} "show slave status\G" | grep -c "Slave_IO_Running: Yes"`


if [ ${MASTER_STATUS} -eq 1 ] && [ ${SLAVE_STATUS} -eq 1 ]; then
    exit 0
else
    exit 1
fi
```


3. 启动keepalived


在主库和从库上分别启动keepalived服务:


```bash
systemctl start keepalived
```


4. 测试


在主库上停止MySQL服务,观察从库是否自动切换为主库。



转载请标明出处【使用keepalived实现MySQL主从模式自动切换数据库】。

《www.micoder.cc》 虚拟化云计算,系统运维,安全技术服务.

网站已经关闭评论