MySQL主从复制【基于GTID复制】

MySQL主从复制:GTID模式详解与实战操作
本文详细介绍了GTID复制在MySQL主从同步中的作用,包括GTID复制的工作原理、配置参数调整以及一个完整的环境搭建与测试案例。通过实例演示了如何开启GTID模式,验证数据同步一致性。

1、GTID复制简介

在主从同步时 GTID_Event 和事务的 Binlog 会一起传递到从库,由中继日志接收,从库在执行的时候使用对应的 GTID 写 binlog;主从同步以后,可以通过 GTID 确定从库目前同步的位置了。
【简单来说:可以通过 GTID 自动找点,无需像之前那样通过 binlog 名 和 position 号找点】

2、GTID复制运行过程

1、master 更新数据时,会在事务前产生 GTID 并一同记录到 binlog 日志中;
2、slave 端的 IO 线程将变更的 binlog写入到本地的 relay-log(中继日志)中;
3、sql 线程从 relay-log 中获取对应的 GTID,对比 slave 端的 binlog 的记录 ;
4、如果有记录,说明该 GTID 的事务已执行,slave 会忽略该 GTID;
5、如果没有记录,slave 会从 relay-log 中执行该 GTID 的事务,并记录到 binlog 中;

3、GTID复制开启参数

//在MySQL配置文件中添加
[mysqld]
gtid-mode=on						//启用GTID
enforce-gtid-consistency=true		//强制GTID的一致性
log-slave-updates=1					//slave更新是否记入日志(1表示记入、0表示不记入)

4、示例

1)环境准备

三台主机:一主、两从
主库(MySQL master)[ip为192.168.25.131]
从库(MySQL slave1)[ip为192.168.25.133]
从库(MySQL slave2)[ip为192.168.25.134]

2)初始化数据【重置所有数据(方便实验)】

//清空MySQL数据目录,否则无法初始化
[root@localhost ~]# rm -rf /var/lib/mysql/\*
//上方语句末尾\*表示将*注释,否则优快云会视为注释,复制至Linux系统需要删除“\”

[root@localhost ~]# mysqld --initialize-insecure --user=mysql --basedir=/usr  --datadir=/var/lib/mysql/ 

3)配置主库

[root@localhost ~]# systemctl stop firewalld	//关闭防火墙,否则主从无法建立连接(有能力者设定防火墙规则放行)

[root@localhost ~]# vim /etc/my.cnf		//修改配置文件(开启binlog参数、设置server-id值)

[mysqld]
log_bin=/var/lib/mysql/mysql-bin	//bin_log指定文件名和文件路径
server_id=131	//MySQL5.5版本后要开启bin_log必须给定一个唯一的服务器id(一般为IPV4地址主机位)

gtid-mode=on
enforce-gtid-consistency=true
log-slave-updates=1

[mysql]
prompt="db01 [\\d] > "

[root@localhost ~]# systemctl restart mysqld
db01 [(none)] > grant replication slave on *.* to "rep"@"192.168.25.%" identified by '123456';
Query OK, 0 rows affected, 1 warning (0.01 sec)

db01 [(none)] > show grants for "rep"@"192.168.25.%";
+--------------------------------------------------------+
| Grants for rep@192.168.25.%                            |
+--------------------------------------------------------+
| GRANT REPLICATION SLAVE ON *.* TO 'rep'@'192.168.25.%' |
+--------------------------------------------------------+
1 row in set (0.00 sec)

4)配置从库

db02 [(none)] > change master to
    -> master_host="192.168.25.131",		#主库IP
    -> master_user="rep",					#同步账号
    -> master_password="123456",			#同步账号的密码
    -> master_auto_position=1;				#自动 position 号(偏移值)【不用填写binlog & position】
Query OK, 0 rows affected, 2 warnings (0.01 sec)

db02 [(none)] > system systemctl stop firewalld		#关闭防火墙

db03 [(none)] > change master to
    -> master_host="192.168.25.131",
    -> master_user="rep",
    -> master_password="123456",
    -> master_auto_position=1;
Query OK, 0 rows affected, 2 warnings (0.00 sec)

db02 [(none)] > system systemctl stop firewalld		#关闭防火墙
#启动从库同步开关
db02 [(none)] > start slave;
Query OK, 0 rows affected (0.00 sec)

db02 [(none)] > show slave status\G		#查看结果
*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: 192.168.25.131
                  Master_User: rep
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: mysql-bin.000002
          Read_Master_Log_Pos: 707
               Relay_Log_File: localhost-relay-bin.000002
                Relay_Log_Pos: 920
        Relay_Master_Log_File: mysql-bin.000002
             Slave_IO_Running: Yes		#此处必须为yes(表示成功)
            Slave_SQL_Running: Yes		#此处必须为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: 707
              Relay_Log_Space: 1131
              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: 0
Master_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: 131
                  Master_UUID: 4a4ec55f-d078-11ec-b9e8-000c29c1f77e
             Master_Info_File: /var/lib/mysql/master.info
                    SQL_Delay: 0
          SQL_Remaining_Delay: NULL
      Slave_SQL_Running_State: Slave has read all relay log; waiting for more updates
           Master_Retry_Count: 86400
                  Master_Bind: 
      Last_IO_Error_Timestamp: 
     Last_SQL_Error_Timestamp: 
               Master_SSL_Crl: 
           Master_SSL_Crlpath: 
           Retrieved_Gtid_Set: 4a4ec55f-d078-11ec-b9e8-000c29c1f77e:1-2		//表示收到的事务(重点)
            Executed_Gtid_Set: 4a4ec55f-d078-11ec-b9e8-000c29c1f77e:1-2,
594ea1be-d078-11ec-96d7-000c2967ad99:1										//表示已执行的事务(重点)
                Auto_Position: 1
         Replicate_Rewrite_DB: 
                 Channel_Name: 
           Master_TLS_Version: 
1 row in set (0.00 sec)

db03 [(none)] > start slave;
Query OK, 0 rows affected (0.00 sec)

db03 [(none)] > show slave status\G		#查看结果
*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: 192.168.25.131
                  Master_User: rep
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: mysql-bin.000002
          Read_Master_Log_Pos: 707
               Relay_Log_File: localhost-relay-bin.000002
                Relay_Log_Pos: 920
        Relay_Master_Log_File: mysql-bin.000002
             Slave_IO_Running: Yes		#此处必须为yes(表示成功)
            Slave_SQL_Running: Yes		#此处必须为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: 707
              Relay_Log_Space: 1131
              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: 0
Master_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: 131
                  Master_UUID: 4a4ec55f-d078-11ec-b9e8-000c29c1f77e
             Master_Info_File: /var/lib/mysql/master.info
                    SQL_Delay: 0
          SQL_Remaining_Delay: NULL
      Slave_SQL_Running_State: Slave has read all relay log; waiting for more updates
           Master_Retry_Count: 86400
                  Master_Bind: 
      Last_IO_Error_Timestamp: 
     Last_SQL_Error_Timestamp: 
               Master_SSL_Crl: 
           Master_SSL_Crlpath: 
           Retrieved_Gtid_Set: 4a4ec55f-d078-11ec-b9e8-000c29c1f77e:1-2		//表示收到的事务(重点)
            Executed_Gtid_Set: 4a4ec55f-d078-11ec-b9e8-000c29c1f77e:1-2,
5fe99a5e-d078-11ec-956b-000c294d6b8d:1										//表示已执行的事务(重点)
                Auto_Position: 1
         Replicate_Rewrite_DB: 
                 Channel_Name: 
           Master_TLS_Version: 
1 row in set (0.00 sec)

5)测试

db01 [(none)] > create database test;
Query OK, 1 row affected (0.00 sec)

db02 [(none)] > show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
| test               |
+--------------------+
5 rows in set (0.00 sec)

db03 [(none)] > show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
| test               |
+--------------------+
5 rows in set (0.00 sec)
db01 [test] > create table t1(id int);
Query OK, 0 rows affected (0.01 sec)

db01 [test] > insert into t1 values(1),(2);
Query OK, 2 rows affected (0.03 sec)
Records: 2  Duplicates: 0  Warnings: 0

db02 [(none)] > use test;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
db02 [test] > select * from t1;
+------+
| id   |
+------+
|    1 |
|    2 |
+------+
2 rows in set (0.00 sec)

db03 [(none)] > use test;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
db03 [test] > select * from t1;
+------+
| id   |
+------+
|    1 |
|    2 |
+------+
2 rows in set (0.00 sec)
db01 [test] > drop database test;
Query OK, 1 row affected (0.00 sec)

db02 [test] > show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
4 rows in set (0.01 sec)

db03 [test] > show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
4 rows in set (0.00 sec)

通过上方测试,通过查看发现所有数据均已同步,主从复制成功

6)查看GTID

db01 [(none)] > show master status;
+------------------+----------+--------------+------------------+------------------------------------------+
| File             | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set                        |
+------------------+----------+--------------+------------------+------------------------------------------+
| mysql-bin.000002 |     1443 |              |                  | 4a4ec55f-d078-11ec-b9e8-000c29c1f77e:1-6 |
+------------------+----------+--------------+------------------+------------------------------------------+
1 row in set (0.00 sec)

db02 [(none)] > show master status;
+------------------+----------+--------------+------------------+----------------------------------------------------------------------------------+
| File             | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set                                                                |
+------------------+----------+--------------+------------------+----------------------------------------------------------------------------------+
| mysql-bin.000002 |     1678 |              |                  | 4a4ec55f-d078-11ec-b9e8-000c29c1f77e:1-6,
594ea1be-d078-11ec-96d7-000c2967ad99:1 |
+------------------+----------+--------------+------------------+----------------------------------------------------------------------------------+
1 row in set (0.00 sec)

db03 [(none)] > show master status;
+------------------+----------+--------------+------------------+----------------------------------------------------------------------------------+
| File             | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set                                                                |
+------------------+----------+--------------+------------------+----------------------------------------------------------------------------------+
| mysql-bin.000002 |     1678 |              |                  | 4a4ec55f-d078-11ec-b9e8-000c29c1f77e:1-6,
5fe99a5e-d078-11ec-956b-000c294d6b8d:1 |
+------------------+----------+--------------+------------------+----------------------------------------------------------------------------------+
1 row in set (0.00 sec)

可以看出三台服务器的GTID是相同的,同时保留自身GTID

<think>我们正在讨论MySQL主从复制中的GTID配置。根据引用内容,GTID(全局事务标识符)是MySQL复制中用于跟踪事务的唯一标识。GTID主从复制相比传统主从复制更易于管理和维护,因为每个事务都有全局唯一的ID。 步骤概述: 1. 配置主库(Master)的my.cnf文件,开启GTID模式。 2. 配置从库(Slave)的my.cnf文件,同样开启GTID模式。 3. 在主库上创建复制用户并授权。 4. 在从库上配置指向主库,并启动复制。 详细步骤: 1. 主库配置(Master): 编辑主库的配置文件(通常为/etc/my.cnf或/etc/mysql/my.cnf),在[mysqld]部分添加以下内容: ``` [mysqld] server_id=1 # 设置服务器唯一ID,主从不能相同 log_bin=mysql-bin # 开启二进制日志 gtid_mode=ON # 开启GTID模式 enforce_gtid_consistency=ON # 强制GTID一致性 ``` 2. 重启主库MySQL服务使配置生效: ```bash systemctl restart mysqld ``` 3. 在主库上创建复制用户并授权: ```sql CREATE USER 'repl'@'%' IDENTIFIED BY 'your_password'; GRANT REPLICATION SLAVE ON *.* TO 'repl'@'%'; FLUSH PRIVILEGES; ``` 4. 从库配置(Slave): 编辑从库的配置文件,在[mysqld]部分添加: ``` [mysqld] server_id=2 # 设置不同的服务器ID log_bin=mysql-bin # 开启二进制日志(可选,但建议开启) gtid_mode=ON enforce_gtid_consistency=ON read_only=ON # 设置从库为只读(推荐) ``` 5. 重启从库MySQL服务: ```bash systemctl restart mysqld ``` 6. 在从库上配置主库信息并启动复制: 使用以下命令连接主库并启动复制: ```sql CHANGE MASTER TO MASTER_HOST='master_ip_address', MASTER_USER='repl', MASTER_PASSWORD='your_password', MASTER_AUTO_POSITION=1; # 使用GTID自动定位,无需指定binlog文件和位置 START SLAVE; ``` 7. 检查从库复制状态: ```sql SHOW SLAVE STATUS\G ``` 查看输出中的`Slave_IO_Running`和`Slave_SQL_Running`是否为`Yes`,以及是否有错误信息。 注意:在配置GTID主从之前,如果主库中已有数据,需要先备份主库数据并恢复到从库,以保证数据一致性。可以使用mysqldump或xtrabackup等工具进行备份恢复,并在备份时加上`--set-gtid-purged=ON`选项。 引用[^1]中提到了在从数据库中查看数据是否同步,可以通过在从库上查询数据来验证同步情况。 引用[^3]提供了主库配置的示例,其中特别强调了开启GTID的两个参数:`gtid_mode=ON`和`enforce-gtid-consistency=ON`(注意在配置文件中应使用下划线,但MySQL也接受减号,不过通常使用下划线)。 引用[^2]概述了主从复制的作用、形式和原理,以及GTID的概念和组成,并简要提到了配置步骤。 以上步骤即为配置MySQL GTID主从复制的基本方法。 相关问题: 1. 如何验证GTID主从复制是否正常工作? 2. 如果主库已有数据,如何初始化从库? 3. GTID主从复制相比传统主从复制有哪些优势?</think>### MySQL主从复制配置GTID的方法和步骤 根据引用内容[^1][^2][^3],GTID(Global Transaction Identifier)主从复制通过全局唯一事务ID简化复制管理,配置步骤如下: #### 一、主库配置 1. **修改配置文件**(如`/etc/my.cnf`): ```ini [mysqld] server_id=10 # 唯一ID(主从不能重复) log_bin=mysql-bin # 启用二进制日志 gtid_mode=ON # 开启GTID模式[^3] enforce_gtid_consistency=ON # 强制GTID一致性[^3] binlog_format=ROW # 推荐使用ROW格式 ``` 2. **重启MySQL服务**: ```bash systemctl restart mysqld ``` 3. **创建复制用户**: ```sql CREATE USER 'repl'@'%' IDENTIFIED BY 'password'; GRANT REPLICATION SLAVE ON *.* TO 'repl'@'%'; FLUSH PRIVILEGES; ``` #### 二、从库配置 1. **修改配置文件**: ```ini [mysqld] server_id=20 # 不同于主库的ID relay_log=mysql-relay-bin read_only=ON # 设置只读[^2] gtid_mode=ON enforce_gtid_consistency=ON ``` 2. **重启MySQL服务**: ```bash systemctl restart mysqld ``` #### 三、初始化数据同步 1. **主库备份**: ```bash mysqldump --all-databases --master-data -u root -p > db_backup.sql ``` 2. **导入从库**: ```bash mysql -u root -p < db_backup.sql ``` #### 四、启动GTID复制 在从库执行: ```sql CHANGE MASTER TO MASTER_HOST='主库IP', MASTER_USER='repl', MASTER_PASSWORD='password', MASTER_AUTO_POSITION=1; # 关键!启用GTID自动定位[^1] START SLAVE; ``` #### 五、验证复制状态 ```sql SHOW SLAVE STATUS\G ``` 检查关键指标: - `Slave_IO_Running: Yes` - `Slave_SQL_Running: Yes` - `Retrieved_Gtid_Set`(已接收事务) - `Executed_Gtid_Set`(已执行事务) #### 六、测试数据同步 在主库插入数据: ```sql INSERT INTO runtime.student(name) VALUES ('test_gtid'); ``` 在从库查询验证(如引用[^1]示例): ```sql SELECT * FROM runtime.student; ``` ### 关键注意事项 1. **GTID组成**:`server_uuid:事务ID`[^2] 2. **一致性要求**:所有节点需同时启用`gtid_mode`和`enforce_gtid_consistency` 3. **故障处理**:出现复制错误时,可通过`SET GLOBAL gtid_purged`跳过事务 > 配置成功后,GTID自动跟踪事务位置,无需手动管理binlog文件和位置[^3]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值