网站建设知识
MySQL主从复制实战
2025-07-22 11:14  点击:0

MySQL主从复制实战 - 基于GTID的复制

基于GTID的复制

简介

基于GTID的复制是MySQL 5.6后新增的复制方式.

GTID (global transaction identifier) 即全局事务ID, 保证了在每个在主库上提交的事务在集群中有一个唯一的ID.

在原来基于日志的复制中, 从库需要告知主库要从哪个偏移量进行增量同步, 如果指定错误会造成数据的遗漏, 从而造成数据的不一致.

而基于GTID的复制中, 从库会告知主库已经执行的事务的GTID的值, 然后主库会将所有未执行的事务的GTID的列表返回给从库. 并且可以保证同一个事务只在指定的从库执行一次.

实战

主库上建立复制账户并授予权限

基于GTID的复制会自动地将没有在从库执行的事务重放, 所以不要在其他从库上建立相同的账号. 如果建立了相同的账户, 有可能造成复制链路的错误.

mysql> start slave;

启动成功后查看slave的状态

mysql> show slave status\G*************************** 1. row ***************************              Slave_IO_State: Queueing master event to the relay log                 Master_Host: master                 Master_User: repl                 Master_Port: 3306               Connect_Retry: 60             Master_Log_File: mysql-bin.000002         Read_Master_Log_Pos: 12793692              Relay_Log_File: relay-bin.000002               Relay_Log_Pos: 1027       Relay_Master_Log_File: mysql-bin.000002            Slave_IO_Running: Yes           Slave_SQL_Running: Yes             Replicate_Do_DB:         Replicate_Ignore_DB:          Replicate_Do_Table:      Replicate_Ignore_Table:     Replicate_Wild_Do_Table: Replicate_Wild_Ignore_Table:                  Last_Errno: 0                  Last_Error:                Skip_Counter: 0         Exec_Master_Log_Pos: 814             Relay_Log_Space: 12794106             Until_Condition: None              Until_Log_File:               Until_Log_Pos: 0          Master_SSL_Allowed: No          Master_SSL_CA_File:          Master_SSL_CA_Path:             Master_SSL_Cert:           Master_SSL_Cipher:              Master_SSL_Key:       Seconds_Behind_Master: 5096Master_SSL_Verify_Server_Cert: No               Last_IO_Errno: 0               Last_IO_Error:              Last_SQL_Errno: 0              Last_SQL_Error: Replicate_Ignore_Server_Ids:            Master_Server_Id: 101                 Master_UUID: a9fd4765-ec70-11e6-b543-0242ac140002            Master_Info_File: mysql.slave_master_info                   SQL_Delay: 0         SQL_Remaining_Delay: NULL     Slave_SQL_Running_State: Reading event from the relay log          Master_Retry_Count: 86400                 Master_Bind:     Last_IO_Error_Timestamp:    Last_SQL_Error_Timestamp:              Master_SSL_Crl:          Master_SSL_Crlpath:          Retrieved_Gtid_Set: a9fd4765-ec70-11e6-b543-0242ac140002:1-39           Executed_Gtid_Set: a9fd4765-ec70-11e6-b543-0242ac140002:1-4               Auto_Position: 1        Replicate_Rewrite_DB:                Channel_Name:          Master_TLS_Version:1 row in set (0.00 sec)

当Slave_IO_Running, Slave_SQL_Running为YES,

且Slave_SQL_Running_State 为Slave has read all relay log; waiting for more updates时表示成功构建复制链路

总结

优点
因为不用手工设置日志偏移量, 可以很方便地进行故障转移 如果启用log_slave_updates那么从库不会丢失主库上的任何修改 缺点
对执行的SQL有一定限制 仅支持MySQL 5.6之后的版本, 而且不建议使用早期5.6版本