Table of Contents
What is GTID
What are the GTID improvements?
How GTID works
One master and one slave GTID copy setup
master configuration
slave configuration
Problems encountered
Home Database Mysql Tutorial How to apply MySQL GTID replication

How to apply MySQL GTID replication

May 27, 2023 am 11:25 AM
mysql gtid

How to apply MySQL GTID replication

Since MySQL 5.6.5, a global transaction identifier (GTID)-based replication method has been introduced. GTID ensures that every transaction submitted to the main database in the cluster has a unique identifier. This method strengthens the primary and secondary consistency, fault recovery and fault tolerance capabilities of the database.

What is GTID

GTID (Global Transaction ID) is the number of a submitted transaction and is a globally unique number. GTID is actually composed of UUID TID. The UUID is the unique identifier of a MySQL instance. The value of TID increases monotonically with each submitted transaction, recording the number of transactions that have been submitted on this instance.

The following is the specific form of a GTID: 3E11FA47-71CA-11E1-9E33-C80AA9429562:23. The colon separates the uuid in front and the TID in the back.

The GTID collection can contain transactions from multiple MySQL instances, separated by commas.

If the ranges of multiple transaction sequence numbers come from the same MySQL instance, each range should be separated by a colon. For example: e6954592-8dba-11e6-af0e-fa163e1cf111:1-5:11-18,e6954592-8dba-11e6-af0e-fa163e1cf3f2:1-27.

What are the GTID improvements?

In the original binary log-based replication, the slave library needs to tell the master library which offset to perform incremental synchronization from. If specified Errors can cause data to be omitted, resulting in data inconsistencies. With the help of GTID, in the event of a master-slave switchover, MySQL's other slave databases can automatically find the correct replication location on the new master database, which greatly simplifies the maintenance of the cluster under complex replication topologies and reduces the occurrence of manual setting of replication locations. Risk of misuse. Using GTID-based replication reduces the risk of data inconsistency by excluding transactions that have already been executed.

Based on gtid set, the master database can accurately know what data is missing from the slave database, and will not provide more or less data to the slave database to avoid wasting network bandwidth.

Mysql master-slave structure has no advantage for GTID in the case of one master and one slave. However, the advantages of the structure with more than two masters are extremely obvious, and the new master can be switched without losing data.

Note: Before building master-slave replication, perform some operations (such as data cleaning, etc.) on an instance that will become the master, and replicate through GTID. These are before the master-slave is established. The operation will also be copied to the slave server, causing the replication to fail. That is to say, replication through GTID always starts from the earliest transaction log, even if these operations are performed before replication. For example, if you perform some drop and delete cleanup operations on server1, and then perform a change operation on server2, server2 will also perform cleanup operations on server1.

How GTID works

  1. #When a transaction is executed and submitted on the main library side, a GTID is generated and recorded in the binlog log.

  2. After the binlog is transferred to the slave and stored in the slave's relaylog, read the value of the GTID and set the gtid_next variable, which tells the slave the next GTID value to be executed.

  3. The sql thread obtains the GTID from the relay log, and then compares the binlog on the slave side to see whether the GTID exists.

  4. If there is a record, it means that the transaction of the GTID has been executed and the slave will ignore it.

  5. If there is no record, the slave will execute the GTID transaction and record the GTID to its own binlog. Before reading and executing the transaction, it will first check that other sessions hold the GTID to ensure Not executed repeatedly.

One master and one slave GTID copy setup

Host planning:

  • master: docker, port 3312

  • slave: docker, port 3313

master configuration

The content of the configuration file my.cnf is as follows:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

$ cat /home/mysql/docker-data/3313/conf/my.cnf

# For advice on how to change settings please see

# http://dev.mysql.com/doc/refman/5.7/en/server-configuration-defaults.html

 

[mysqld]

#

# Remove leading # and set to the amount of RAM for the most important data

# cache in MySQL. Start at 70% of total RAM for dedicated server, else 10%.

# innodb_buffer_pool_size = 128M

#

# Remove leading # to turn on a very important data integrity option: logging

# changes to the binary log between backups.

# log_bin

#

# Remove leading # to set options mainly useful for reporting servers.

# The server defaults are faster for transactions and fast SELECTs.

# Adjust sizes as needed, experiment to find the optimal values.

# join_buffer_size = 128M

# sort_buffer_size = 2M

# read_rnd_buffer_size = 2M

#datadir=/home/mysql/docker-data/3307/data

#socket=/home/mysql/docker-data/3307/mysql.sock

 

character_set_server=utf8

init_connect='SET NAMES utf8'

 

# Disabling symbolic-links is recommended to prevent assorted security risks

symbolic-links=0

 

#log-error=/home/mysql/docker-data/3307/logs/mysqld.log

#pid-file=/home/mysql/docker-data/3307/mysqld.pid

lower_case_table_names=1

server-id=1403311

log-bin=mysql-bin

binlog-format=ROW

auto_increment_increment=1

auto_increment_offset=1

# 开启gtid

gtid_mode=ON

enforce-gtid-consistency=true

 

#rpl_semi_sync_master_enabled=1

#rpl_semi_sync_master_timeout=10000

Copy after login

Create a docker instance:

1

$ docker run --name mysql3312 -p 3312:3306 --privileged=true -ti -e MYSQL_ROOT_PASSWORD=root -e MYSQL_DATABASE=order -e MYSQL_USER=user -e MYSQL_PASSWORD=pass -v /home/mysql/docker-data/3312/conf:/etc/mysql/conf.d -v /home/mysql/docker-data/3312/data/:/var/lib/mysql -v /home/mysql/docker-data/3312/logs/:/var/log/mysql -d mysql:5.7

Copy after login

Add a user for replication and authorize:

1

2

3

4

5

mysql> GRANT REPLICATION SLAVE,FILE,REPLICATION CLIENT ON *.* TO 'repluser'@'%' IDENTIFIED BY '123456';

Query OK, 0 rows affected, 1 warning (0.01 sec)

 

mysql> FLUSH PRIVILEGES;

Query OK, 0 rows affected (0.01 sec)

Copy after login

slave configuration

The content of the configuration file my.cnf is consistent with the master, pay attention to modifying the server -id, keep it unique.

Create docker instance:

1

$ docker run --name mysql3313 -p 3313:3306 --privileged=true -ti -e MYSQL_ROOT_PASSWORD=root -e MYSQL_DATABASE=order -e MYSQL_USER=user -e MYSQL_PASSWORD=pass -v /home/mysql/docker-data/3313/conf:/etc/mysql/conf.d -v /home/mysql/docker-data/3313/data/:/var/lib/mysql -v /home/mysql/docker-data/3313/logs/:/var/log/mysql -d mysql:5.7

Copy after login

Enable GTID synchronization:

1

2

3

4

5

mysql> change master to master_host='172.23.252.98',master_port=3310,master_user='repluser',master_password='123456',master_auto_position=1;

Query OK, 0 rows affected, 2 warnings (0.02 sec)

 

mysql> start slave;

Query OK, 0 rows affected (0.02 sec)

Copy after login

View status:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

mysql> show master status;

+------------------+----------+--------------+------------------+----------------------------------------+

| File             | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set                      |

+------------------+----------+--------------+------------------+----------------------------------------+

| mysql-bin.000008 |      154 |              |                  | cd2eaa0a-7a59-11ec-b3b4-0242ac110002:1 |

+------------------+----------+--------------+------------------+----------------------------------------+

1 row in set (0.00 sec)

 

mysql> show slave status\G;

*************************** 1. row ***************************

               Slave_IO_State: Waiting for master to send event

                  Master_Host: 172.23.252.98

                  Master_User: repluser

                  Master_Port: 3312

                Connect_Retry: 60

              Master_Log_File: mysql-bin.000006

          Read_Master_Log_Pos: 419

               Relay_Log_File: 5dfbef024732-relay-bin.000003

                Relay_Log_Pos: 632

        Relay_Master_Log_File: mysql-bin.000006

             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: 419

              Relay_Log_Space: 846

              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: 1403311

                  Master_UUID: cd2eaa0a-7a59-11ec-b3b4-0242ac110002

             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: cd2eaa0a-7a59-11ec-b3b4-0242ac110002:1

            Executed_Gtid_Set: cd2eaa0a-7a59-11ec-b3b4-0242ac110002:1

                Auto_Position: 1

         Replicate_Rewrite_DB:

                 Channel_Name:

           Master_TLS_Version:

1 row in set (0.00 sec)

Copy after login

Insert data in the master.order table:

1

mysql> insert into t_order values(4,"V");

Copy after login

Found that the data has been synchronized to the slave:

1

2

3

4

5

6

7

mysql> select * from order.t_order;

+------+------+

| id   | name |

+------+------+

|    4 | V    |

+------+------+

3 rows in set (0.00 sec)

Copy after login

Stop the slave first, and then insert data into the master.order table:

1

mysql> insert into t_order values(5,"X");

Copy after login

Then start the slave, and find that the data has been automatically synchronized:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

mysql> stop slave;

Query OK, 0 rows affected (0.01 sec)

 

mysql> select * from order.t_order;

+------+------+

| id   | name |

+------+------+

|    4 | V    |

+------+------+

3 rows in set (0.00 sec)

 

mysql> start slave;

Query OK, 0 rows affected (0.02 sec)

 

mysql> select * from order.t_order;

+------+------+

| id   | name |

+------+------+

|    4 | V    |

|    5 | X    |

+------+------+

4 rows in set (0.00 sec)

Copy after login

Problems encountered

Show slave status on the slave server:

1

Fatal error: The slave I/O thread stops because master and slave have equal MySQL server UUIDs; these UUIDs must be different for replication to work.

Copy after login

First check whether the server_id of the master and slave are consistent. If they are consistent, modify the server_id in the my.cnf file. Field:

1

mysql> show variables like 'server_id';

Copy after login

Then check whether the uuid of master and slave are consistent:

1

mysql> show variables like '%uuid%';

Copy after login

If the uuid is consistent, modify the auto.cnf file in the data directory, copy the entire data directory, and replace the auto.cnf file I also copied it, and it records the uuid of the database. The uuid of each library should be different.

The above is the detailed content of How to apply MySQL GTID replication. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MySQL: Simple Concepts for Easy Learning MySQL: Simple Concepts for Easy Learning Apr 10, 2025 am 09:29 AM

MySQL is an open source relational database management system. 1) Create database and tables: Use the CREATEDATABASE and CREATETABLE commands. 2) Basic operations: INSERT, UPDATE, DELETE and SELECT. 3) Advanced operations: JOIN, subquery and transaction processing. 4) Debugging skills: Check syntax, data type and permissions. 5) Optimization suggestions: Use indexes, avoid SELECT* and use transactions.

How to open phpmyadmin How to open phpmyadmin Apr 10, 2025 pm 10:51 PM

You can open phpMyAdmin through the following steps: 1. Log in to the website control panel; 2. Find and click the phpMyAdmin icon; 3. Enter MySQL credentials; 4. Click "Login".

MySQL: An Introduction to the World's Most Popular Database MySQL: An Introduction to the World's Most Popular Database Apr 12, 2025 am 12:18 AM

MySQL is an open source relational database management system, mainly used to store and retrieve data quickly and reliably. Its working principle includes client requests, query resolution, execution of queries and return results. Examples of usage include creating tables, inserting and querying data, and advanced features such as JOIN operations. Common errors involve SQL syntax, data types, and permissions, and optimization suggestions include the use of indexes, optimized queries, and partitioning of tables.

How to use single threaded redis How to use single threaded redis Apr 10, 2025 pm 07:12 PM

Redis uses a single threaded architecture to provide high performance, simplicity, and consistency. It utilizes I/O multiplexing, event loops, non-blocking I/O, and shared memory to improve concurrency, but with limitations of concurrency limitations, single point of failure, and unsuitable for write-intensive workloads.

Why Use MySQL? Benefits and Advantages Why Use MySQL? Benefits and Advantages Apr 12, 2025 am 12:17 AM

MySQL is chosen for its performance, reliability, ease of use, and community support. 1.MySQL provides efficient data storage and retrieval functions, supporting multiple data types and advanced query operations. 2. Adopt client-server architecture and multiple storage engines to support transaction and query optimization. 3. Easy to use, supports a variety of operating systems and programming languages. 4. Have strong community support and provide rich resources and solutions.

MySQL's Place: Databases and Programming MySQL's Place: Databases and Programming Apr 13, 2025 am 12:18 AM

MySQL's position in databases and programming is very important. It is an open source relational database management system that is widely used in various application scenarios. 1) MySQL provides efficient data storage, organization and retrieval functions, supporting Web, mobile and enterprise-level systems. 2) It uses a client-server architecture, supports multiple storage engines and index optimization. 3) Basic usages include creating tables and inserting data, and advanced usages involve multi-table JOINs and complex queries. 4) Frequently asked questions such as SQL syntax errors and performance issues can be debugged through the EXPLAIN command and slow query log. 5) Performance optimization methods include rational use of indexes, optimized query and use of caches. Best practices include using transactions and PreparedStatemen

MySQL and SQL: Essential Skills for Developers MySQL and SQL: Essential Skills for Developers Apr 10, 2025 am 09:30 AM

MySQL and SQL are essential skills for developers. 1.MySQL is an open source relational database management system, and SQL is the standard language used to manage and operate databases. 2.MySQL supports multiple storage engines through efficient data storage and retrieval functions, and SQL completes complex data operations through simple statements. 3. Examples of usage include basic queries and advanced queries, such as filtering and sorting by condition. 4. Common errors include syntax errors and performance issues, which can be optimized by checking SQL statements and using EXPLAIN commands. 5. Performance optimization techniques include using indexes, avoiding full table scanning, optimizing JOIN operations and improving code readability.

Monitor Redis Droplet with Redis Exporter Service Monitor Redis Droplet with Redis Exporter Service Apr 10, 2025 pm 01:36 PM

Effective monitoring of Redis databases is critical to maintaining optimal performance, identifying potential bottlenecks, and ensuring overall system reliability. Redis Exporter Service is a powerful utility designed to monitor Redis databases using Prometheus. This tutorial will guide you through the complete setup and configuration of Redis Exporter Service, ensuring you seamlessly build monitoring solutions. By studying this tutorial, you will achieve fully operational monitoring settings

See all articles