MySQL master-slave replication (2)-the construction of a master-slave architecture

MySQL master-slave replication (2)-the construction of a master-slave architecture

The working principle of MySQL master-slave replication is as follows:
(1) The master-slave replication between Mysql servers is based on the binary log. The master server uses the binary log to record changes in the database. The slave server reads and executes the log file to keep the balance. The data of the main server is consistent.
(2) When using the binary log, all operations of the master server will be recorded, and then the slave server will receive a copy of the log. The slave server can specify which type of event (insert data, update data, delete data) in the log is executed, and all statements in the log will be executed by default.
(3) Each slave server will record information about the binary log (file name and processed statements), which means that different slave servers can execute different parts of the same binary log, and the slave server can connect or disconnect at any time Connection to the server.
(4) The master server and each slave server must be configured with a unique server-id. Each slave server needs to use the CHANGE MASTER TO statement to configure the ip address of the master server to be connected, the log file name and the log Location and other information.

The steps of MySQL master-slave replication configuration are as follows:

1. System environment

MySQL version: MySQL5.7

Linux version: CentOS7.0

Main database address: 192.168.1.11

Slave database address: 192.168.1.12; 192.168.1.13

Two, configure the main database

1. Modify the configuration file

Find the configuration file my.cnf of the main database and add the following content in the [mysqld] section:

[root@Mysql11 ~]# vim /etc/my.cnf

[mysqld]
.........
server-id=1  ### 服务器ID
log-bin=mysql-bin  ### 开启binlog
binlog_format=mixed   ### binlog模式为mixed
### 在ROW模式下,即使我们只更新了一条记录的其中某个字段,也会记录每个字段变更前后的值,binlog日志会很大。这个行为可以通过binlog_row_image参数控制,该参数的取值如下:
### FULL(默认值):记录列的所有修改,即使字段没有发生变更也会记录。
### MINIMAL:只记录修改的列。
binlog_row_image=MINIMAL
## 在Row模式下,binlog只记录数据的改变。使用binlog_rows_query_log_events参数也可以记录SQL。参数的默认为值为FALSE,如果为true的情况下,会通过Rows Query Event事件来记录SQL。
binlog-rows-query-log_events=1
### 设置同步时需要忽略哪些数据库 
## 一般同步不要同步mysql库,用户名和密码信息在mysql数据库中
binlog-ignore-db=mysql
binlog-ignore-db=sys
........

After the configuration is complete, restart the mysql service and check the binlog log file information:

[root@Mysql11 ~]# ll /var/lib/mysql/mysql-bin*
-rw-r-----. 1 mysql mysql   923 7月   3 23:19 /var/lib/mysql/mysql-bin.000001
-rw-r-----. 1 mysql mysql   266 7月   5 10:16 /var/lib/mysql/mysql-bin.index

2. Create a copy user

Each slave server needs an account name and password to connect to the master server. You can create an account for each slave server, or you can make all servers use the same account. This account can be used by all IP addresses under the [192.168.1] network segment, and can only perform master-slave synchronization without other permissions.

mysql> set global validate_password_policy=low;
Query OK, 0 rows affected (0.00 sec)

mysql> set global validate_password_length=4;
Query OK, 0 rows affected (0.00 sec)

mysql> grant replication slave on *.* to 'repl'@'192.168.1.%' identified by '123456';
Query OK, 0 rows affected, 1 warning (0.02 sec)

mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)

mysql> select host,user,authentication_string from mysql.user;
+-------------+---------------+-------------------------------------------+
| host        | user          | authentication_string                     |
+-------------+---------------+-------------------------------------------+
| localhost   | root          | *6BB4837EB74329105EE4568DDA7DC67ED2CA2AD9 |
| localhost   | mysql.session | *THISISNOTAVALIDPASSWORDTHATCANBEUSEDHERE |
| localhost   | mysql.sys     | *THISISNOTAVALIDPASSWORDTHATCANBEUSEDHERE |
| %           | wgx           | *6BB4837EB74329105EE4568DDA7DC67ED2CA2AD9 |
| 192.168.1.% | repl          | *6BB4837EB74329105EE4568DDA7DC67ED2CA2AD9 |
+-------------+---------------+-------------------------------------------+
5 rows in set (0.00 sec)

3. Export database data

(1) Before exporting the database, lock the database to prevent any write operations to the database.

mysql> flush tables with read lock;
Query OK, 0 rows affected (0.01 sec)

mysql> use hist;
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
mysql> drop table t1;
ERROR 1223 (HY000): Can't execute the query because you have a conflicting read lock

(2) Export all database data in the main database

[root@Mysql11 ~]# mysqldump -uroot -p123456 --all-databases --master-data=2 --events > /tmp/all_bak.sql

(3) Copy the backup master database data to the slave database

[root@Mysql11 ~]# scp /tmp/all_bak.sql 192.168.1.12:/tmp/
[email protected]'s password: 
all_bak.sql                                          100%  834KB 833.7KB/s   00:00    
[root@Mysql11 ~]# 

(4) Unlock and view binary log information

mysql> unlock tables;
Query OK, 0 rows affected (0.00 sec)

mysql> show master status;
+------------------+----------+--------------+------------------+-------------------+
| File             | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set |
+------------------+----------+--------------+------------------+-------------------+
| mysql-bin.000014 |      599 |              |                  |                   |
+------------------+----------+--------------+------------------+-------------------+
1 row in set (0.00 sec)

Three, configure the slave database

1. Modify the configuration file

Find the configuration file my.cnf of the slave database and add the following content in the [mysqld] section:

[root@Mysql11 ~]# vim /etc/my.cnf

[mysqld]
.........
server-id=2  ### 服务器ID,每个服务器上配置的server-id都必须不一致
relay-log=mysql-relay-log  ### 开启relay log
........

Note: The slave server can also configure the log-bin option as required.

After the configuration is complete, restart the mysql service and check the relay log file information:

[root@localhost ~]# ll /var/lib/mysql/mysql-relay-log*
-rw-r-----. 1 mysql mysql 177 7月   5 11:00 /var/lib/mysql/mysql-relay-log.000001
-rw-r-----. 1 mysql mysql  25 7月   5 11:00 /var/lib/mysql/mysql-relay-log.index

2. Import the data on the main server

[root@localhost ~]# mysql -uroot -p123456 < /tmp/all_bak.sql 

(1) View the database information of the main server

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| hist               |
| mysql              |
| performance_schema |
| sys                |
| wanggx             |
+--------------------+
6 rows in set (0.00 sec)

(2) View the database information of the slave server

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| hist               |
| mysql              |
| performance_schema |
| sys                |
| wanggx             |
+--------------------+
6 rows in set (0.00 sec)

3. Configure master-slave synchronization parameters

Execute the following commands on the slave server:

--master_log_file和master_log_pos两个参数的取值可以在主库导出数据时使用show master logs命令得到
--也可以在主库导出数据库时添加参数【--master-data=2】得到
change master to 
master_host='192.168.1.11',
master_port=3306,
master_user='repl',
master_password='123456',
master_log_file='mysql-bin.000014',
master_log_pos=599;

4. Turn on the service from the library (start IO and SQL threads)

mysql> start slave;
Query OK, 0 rows affected (0.01 sec)

5. View the status of master-slave replication

mysql> show slave status\G
*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: 192.168.1.11
                  Master_User: repl
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: mysql-bin.000014
          Read_Master_Log_Pos: 599
               Relay_Log_File: mysql-relay-log.000002
                Relay_Log_Pos: 320
        Relay_Master_Log_File: mysql-bin.000014
--###############  Slave_IO_Running 和 Slave_SQL_Running 两个都为yes表示正常 #############
             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: 599
              Relay_Log_Space: 527
              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: 1
                  Master_UUID: 95cfc8eb-2d58-11ea-840b-000c296166d5
             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: 
            Executed_Gtid_Set: 
                Auto_Position: 0
         Replicate_Rewrite_DB: 
                 Channel_Name: 
           Master_TLS_Version: 
1 row in set (0.00 sec)

Four, verification results

1. Perform data operations on the main library

Create a table t222 in the hist database and enter the data

mysql> use hist;
Database changed
mysql> show tables;
+----------------+
| Tables_in_hist |
+----------------+
| course         |
| dept           |
| score          |
| stu            |
| t1             |
+----------------+
5 rows in set (0.00 sec)

mysql> 
mysql> 
mysql> create table t222(id int auto_increment primary key,name char(20),age int);
Query OK, 0 rows affected (0.03 sec)

mysql> insert into t222(name,age) values('Jack',20);
Query OK, 1 row affected (0.02 sec)

mysql> insert into t222(name,age) values('Mary',21);
Query OK, 1 row affected (0.03 sec)

mysql> insert into t222(name,age) values('Tom',18);
Query OK, 1 row affected (0.01 sec)

mysql> select * from t222;
+----+------+------+
| id | name | age  |
+----+------+------+
|  1 | Jack |   20 |
|  2 | Mary |   21 |
|  3 | Tom  |   18 |
+----+------+------+
3 rows in set (0.00 sec)

2. View data information from the library

mysql> use hist;
Database changed
mysql> show tables;
+----------------+
| Tables_in_hist |
+----------------+
| course         |
| dept           |
| score          |
| stu            |
| t1             |
| t222           |
+----------------+
6 rows in set (0.00 sec)

mysql> select * from t222;
+----+------+------+
| id | name | age  |
+----+------+------+
|  1 | Jack |   20 |
|  2 | Mary |   21 |
|  3 | Tom  |   18 |
+----+------+------+
3 rows in set (0.00 sec)

If you want to create multiple slave libraries, the process of creating other slave libraries is exactly the same as that of the first slave library.

Guess you like

Origin blog.csdn.net/weixin_44377973/article/details/107136733