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 的序号递增 。
文章插图
停止主库 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 Monitor
Loaded: loaded (/usr/lib/systemd/system/keepalived.service; enabled; vendor preset: disabled)
Active: active (running) since 五 2021-09-10 21:42:11 CST; 3min 59s ago
Docs: man:keepalived(8)
man:keepalived.conf(5)
man:genhash(1)
https://keepalived.org
Process: 13365 ExecStart=/software/keepalived/sbin/keepalived $KEEPALIVED_OPTIONS (code=exited, status=0/SUCCESS)
Main PID: 13367 (keepalived)
Memory: 1.0M
CGroup: /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 30
9月 10 21:42:20 mysql-master Keepalived_vrrp[13368]: Sending gratuitous ARP on ens192 for 192.168.1.38
9月 10 21:42:20 mysql-master Keepalived_vrrp[13368]: Sending gratuitous ARP on ens192 for 192.168.1.38
9月 10 21:42:20 mysql-master Keepalived_vrrp[13368]: Sending gratuitous ARP on ens192 for 192.168.1.38
9月 10 21:42:20 mysql-master Keepalived_vrrp[13368]: Sending gratuitous ARP on ens192 for 192.168.1.38
9月 10 21:42:20 mysql-master Keepalived_vrrp[13368]: Sending gratuitous ARP on ens192 for 192.168.1.38
9月 10 21:45:47 mysql-master Keepalived_vrrp[13368]: Track script chk_mysql is already running, expect idle - skipping run
9月 10 21:45:47 mysql-master Keepalived_vrrp[13368]: VRRP_Script(chk_mysql) timed_out
9月 10 21:45:47 mysql-master Keepalived_vrrp[13368]: (v_mysql_1) Entering FAULT STATE
9月 10 21:45:47 mysql-master Keepalived_vrrp[13368]: (v_mysql_1) sent 0 priority
9月 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
推荐阅读
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- 被记大过了,一个操作把MySQL主从复制整崩了……
- 大厂高频:讲一下MySQL主从复制
- MySQL面试常见问题解析:掌握这10个问题,事半功倍!
- MySQL如何支撑每秒百万QPS?
- 从MySQL到OBOracle:如何处理自增列?
- MySQL分库分表全攻略:从小白到大神的进阶指南!
- 一次MySQL主从同步异常,扒个底朝天都没排查出来……
- MySQL关联查询时,为什么建议小表驱动大表?这样做有什么好处
- MySQL 驱动中虚引用 GC 耗时优化与源码分析
- Mysql的存储引擎有哪些?