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

root@192.168.1.38 (none) 09:11:13>select @@hostname;+--------------+| @@hostname|+--------------+| mysql-master |+--------------+1 row in set (0.01 sec)root@192.168.1.38 (none) 09:11:26>
复制代码 
客户端创建表并插入数据 。
 
create database testdb;create table testdb.data01( id int not null primary key auto_increment, name varchar(60), age int); insert into testdb.data01 (name,age) values('tom',18),('jack',17),('rock',16),('james',15),('cris',20);
复制代码 
此时分别登录主库 A 和主库 B 查看 testdb.data01 表中的数据,可以确定主库 A 和主库 B 目前数据是同步的 。并且查看表中的内容可以发现主键是以 2 为间隔递增的,这是为了防止主从切换时插入数据产生主键冲突 。主库 A 的主键会以 1,3,5,7,9 的序号递增 。假如在序号为 9 时发生主从切换,新的主库(主库 A)的主键会以 10,12,14,16,18 的序号递增 。
 

MySQL + Keepalived 双主热备搭建

文章插图
停止主库 A,模拟故障切换[root@mysql-master ~]# systemctl stop mysql_3308.service
复制代码 
在主库 A 的机器上查看 keepalived 状态,可以看到 keepalived 的优先级被设置为 0,此时虚拟 IP 将会飘到主库 B 的机器上 。
 
[root@mysql-master tmp]# systemctl status keepalived.service ● keepalived.service - LVS and VRRP High Availability MonitorLoaded: loaded (/usr/lib/systemd/system/keepalived.service; enabled; vendor preset: disabled)Active: active (running) since 五 2021-09-10 21:42:11 CST; 3min 59s agoDocs: man:keepalived(8)man:keepalived.conf(5)man:genhash(1)https://keepalived.orgProcess: 13365 ExecStart=/software/keepalived/sbin/keepalived $KEEPALIVED_OPTIONS (code=exited, status=0/SUCCESS) Main PID: 13367 (keepalived)Memory: 1.0MCGroup: /system.slice/keepalived.service├─13367 /software/keepalived/sbin/keepalived -D├─13368 /software/keepalived/sbin/keepalived -D├─14761 /bin/bash /etc/keepalived/check_mysql.sh└─14778 sleep 309月 10 21:42:20 mysql-master Keepalived_vrrp[13368]: Sending gratuitous ARP on ens192 for 192.168.1.389月 10 21:42:20 mysql-master Keepalived_vrrp[13368]: Sending gratuitous ARP on ens192 for 192.168.1.389月 10 21:42:20 mysql-master Keepalived_vrrp[13368]: Sending gratuitous ARP on ens192 for 192.168.1.389月 10 21:42:20 mysql-master Keepalived_vrrp[13368]: Sending gratuitous ARP on ens192 for 192.168.1.389月 10 21:42:20 mysql-master Keepalived_vrrp[13368]: Sending gratuitous ARP on ens192 for 192.168.1.389月 10 21:45:47 mysql-master Keepalived_vrrp[13368]: Track script chk_mysql is already running, expect idle - skipping run9月 10 21:45:47 mysql-master Keepalived_vrrp[13368]: VRRP_Script(chk_mysql) timed_out9月 10 21:45:47 mysql-master Keepalived_vrrp[13368]: (v_mysql_1) Entering FAULT STATE9月 10 21:45:47 mysql-master Keepalived_vrrp[13368]: (v_mysql_1) sent 0 priority9月 10 21:45:47 mysql-master Keepalived_vrrp[13368]: (v_mysql_1) removing VIPs.
复制代码 
查看主库 B 机器网卡的地址,发现虚拟 IP 已经切换到主库 B 上了 。当发生主从切换时,主库 B 的脚本会执行 reset slave all,停止向主库 A 的同步,防止原主库 A 恢复后数据意外同步 。
 
[root@mysql-slave keepalived]# ip addr


推荐阅读