- 深入理解MySQL主从原理
- 高鹏
- 420字
- 2025-02-21 07:58:42
1.4.3 搭建GTID AUTO_POSITION MODE的主从
在这一部分中,获取gtid-purged变量是需要注意的地方,也是笔者在线上遇到的一个“坑”,这个“坑”还比较普遍。简单来说,就是在MySQL 5.7的某些版本中,导入数据会覆盖原本命令set gtid_purged的设置,而gtid_executed表并不是实时更新的,因此在从库重启后可能导致数据重复拉取,进而导致主从同步报错。
注意,主备库必须开启GTID并设置好server_id:

同时,主从库都开启 binary log。如果不设置级联从库,那么从库不需要开启参数log_slave_updates。
(1)建立复制用户并且授权。

(2)导出数据。

(3)从库导入数据。
使用命令mysql-e "source xxx.sql" 导入数据。
(4)从库执行reset master命令。
这一步主要防止gtid_executed表在导入数据的过程中被覆盖,我们在MySQL 5.7的某些版本中遇到过这种情况。一旦从库再次重启,读取 gtid_executed 表就会得到错误的 gtid_executed变量,进而导致从库启动失败。因此最好重新设置gtid_purged变量。

(5)提取gtid_purged变量,并且执行。
使用head-n 40命令可以快速得到gtid_purged变量,例如:

执行

即可,完成本步骤后,mysql.gtid_executed表会重构,这个我们在1.2节的通用修改时机中已经讨论过了。
(6)使用MASTER_AUTO_POSITION建立同步。


(7)启动slave。
