Experimento de replicação mestre-escravo MySQL


Preparação do experimento:

2 servidores MySQL:
mestre: 192.168.78.132
escravo: 192.168.78.148

Princípio de replicação mestre-escravo

  1. Habilite o log binário no mestre
  2. Quando os dados do mestre forem alterados, um log binário será gerado.
  3. O thread de despejo no mestre notificará o thread io no escravo para obter o log binário e, em seguida, gravá-lo no log de retransmissão do escravo.Em seguida, o thread SQL lerá o log de retransmissão recém-gerado e reproduzirá as operações no log binário, conseguindo assim que o escravo e os dados no mestre sejam exatamente os mesmos, mantendo a consistência.

1. Habilite logs binários

Habilite o log binário no servidor mestre,server_id=1

[root@mysql-master ~]# vim /etc/my.cnf
[mysqld]
...
#log bin
log_bin
server_id = 1

O log binário também pode ser habilitado no servidor escravo.server_id=2

[root@mysql-slave ~]# vim /etc/my.cnf
[mysqld]
...
#log bin
log_bin
server_id = 2

2. Sincronize os dados do banco de dados

Exporte o conteúdo do banco de dados do servidor mestre e importe-o para o servidor escravo

1.Exportar dados no Master

[root@mysql-master ~]# mysqldump -uroot -p"Sanchuang123#" --all-databases >/backup/all_db.sql
mysqldump: [Warning] Using a password on the command line interface can be insecure.

2. Importe dados para o escravo

Carregue o arquivo de dados para o servidor escravo e importe os dados para obter dados iniciais consistentes nos servidores mestre e escravo:
Operação no servidor mestre:

#需要先建立免密通道
[root@mysql-master ~]#  scp /backup/all_db.sql 192.168.78.148:/root
all_db.sql                                                               100%  885KB  79.4MB/s   00:00 

Operação no servidor escravo:

[root@mysql-slave ~]# mysql -uroot -p'Sanchuang123#' <all_db.sql 
mysql: [Warning] Using a password on the command line interface can be insecure.

3. Crie um novo usuário autorizado

Atualize o MySQL no servidor mestre para gerar um novo log para facilitar as operações subsequentes:

root@(none) 19:33  mysql>flush logs;
Query OK, 0 rows affected (0.01 sec)

root@(none) 19:36  mysql>show master status;	#查看当前正在使用的二进制日志文件
+-------------------------+----------+--------------+------------------+-------------------+
| File                    | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set |
+-------------------------+----------+--------------+------------------+-------------------+
| mysql-master-bin.000003 |      154 |              |                  |                   |
+-------------------------+----------+--------------+------------------+-------------------+
1 row in set (0.00 sec)

Crie um novo usuário no MySQL no servidor mestre:

root@(none) 19:36  mysql>grant replication slave on *.* to 'sc'@'192.168.78.%' identified by 'Sanchuang123#';
Query OK, 0 rows affected, 1 warning (0.00 sec)

root@(none) 19:41  mysql>flush privileges;	#刷新 MySQL 权限
Query OK, 0 rows affected (0.00 sec)

root@(none) 19:42  mysql>show show grants for 'sc'@'192.168.78.%';			#用于显示指定用户在 MySQL 中的授权信息
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'show grants for 'sc'@'192.168.78.%'' at line 1
root@(none) 19:42  mysql>show grants for 'sc'@'192.168.78.%';
+-------------------------------------------------------+
| Grants for sc@192.168.78.%                            |
+-------------------------------------------------------+
| GRANT REPLICATION SLAVE ON *.* TO 'sc'@'192.168.78.%' |
+-------------------------------------------------------+
1 row in set (0.01 sec)

4. Configure no servidor escravo

root@(none) 19:58  mysql>CHANGE MASTER TO MASTER_HOST='192.168.78.132' ,
    ->  MASTER_USER='sc',		#创建的授权用户
    ->  MASTER_PASSWORD='Sanchuang123#',		#密码
    ->  MASTER_PORT=3306,	#master的MySQL端口号
    ->  MASTER_LOG_FILE='mysql-master-bin.000003',	#master正在使用的二进制文件
    ->  MASTER_LOG_POS=154;	#二进制文件现在的pos
Query OK, 0 rows affected, 2 warnings (0.00 sec)

Verifique o status do servidor escravo:

root@(none) 19:58  mysql>show slave status\G;
*************************** 1. row ***************************
               Slave_IO_State: 
                  Master_Host: 192.168.78.132
                  Master_User: sc
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: mysql-master-bin.000003
          Read_Master_Log_Pos: 154
               Relay_Log_File: mysql-slave-relay-bin.000001
                Relay_Log_Pos: 4
        Relay_Master_Log_File: mysql-master-bin.000003
             Slave_IO_Running: No	#从服务器的IO线程没有起来
            Slave_SQL_Running: No	#从服务器的SQL线程没有起来

Inicie o thread SQL:

root@(none) 20:01  mysql>stop slave;	#停止从服务器上的主从复制
Query OK, 0 rows affected (0.00 sec) 	

root@(none) 20:03  mysql>start slave;	#开启从服务器上的主从复制
Query OK, 0 rows affected (0.00 sec)
root@(none) 20:03  mysql>show slave status\G;
*************************** 1. row ***************************
               Slave_IO_State: 
                  Master_Host: 192.168.78.132
                  Master_User: sc
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: mysql-master-bin.000003
          Read_Master_Log_Pos: 154
               Relay_Log_File: mysql-slave-relay-bin.000001
                Relay_Log_Pos: 4
        Relay_Master_Log_File: mysql-master-bin.000003
             Slave_IO_Running: No
            Slave_SQL_Running: Yes		#发现sql线程开启成功,io没有成功
              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: 154
              Relay_Log_Space: 154
              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: NULL
Master_SSL_Verify_Server_Cert: No
                Last_IO_Errno: 1593
                Last_IO_Error: 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.		#发现io不成功是uuid问题
               Last_SQL_Errno: 0
               Last_SQL_Error: 
  Replicate_Ignore_Server_Ids: 
             Master_Server_Id: 1
                  Master_UUID: 
             Master_Info_File: /data/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: 230717 20:03:35
     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)

ERROR: 
No query specified

Resolva o mesmo problema com UUID:

root@(none) 20:07  mysql> show variables like "%uuid%";
+---------------+--------------------------------------+
| Variable_name | Value                                |
+---------------+--------------------------------------+
| server_uuid   | 8cccc5f7-be7a-11ed-8855-000c29398d80 |
+---------------+--------------------------------------+
1 row in set (0.00 sec)

Basta modificar alguns caracteres, apenas torná-los diferentes dos do servidor principal:

[root@mysql-slave ~]# cd /data/mysql	#MySQL数据目录
[root@mysql-slave mysql]# vim auto.cnf 
[auto]
server-uuid=8cccc5f7-be7a-11ed-8855-000c29398d81
[root@mysql-slave mysql]# service mysqld restart
Shutting down MySQL.... SUCCESS! 
Starting MySQL. SUCCESS! 

Problema resolvido com sucesso:

root@(none) 20:09  mysql>show slave status\G;
ERROR 2006 (HY000): MySQL server has gone away
No connection. Trying to reconnect...
Connection id:    4
Current database: *** NONE ***

*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: 192.168.78.132
                  Master_User: sc
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: mysql-master-bin.000003
          Read_Master_Log_Pos: 598
               Relay_Log_File: mysql-slave-relay-bin.000003
                Relay_Log_Pos: 771
        Relay_Master_Log_File: mysql-master-bin.000003
             Slave_IO_Running: Yes
            Slave_SQL_Running: Yes

Após sucesso, visualize o arquivo:

[root@mysql-slave mysql]# cat master.info 
25
mysql-master-bin.000003
598
192.168.78.132
sc
Sanchuang123#
3306
60
0





0
30.000

0
8cccc5f7-be7a-11ed-8855-000c29398d80
86400


0


[root@mysql-slave mysql]# cat relay-log.info 
7
./mysql-slave-relay-bin.000003
771
mysql-master-bin.000003
598
0
0
1


Como o Mestre sabe quais servidores escravos existem?

root@(none) 19:51  mysql>SHOW SLAVE HOSTS;
+-----------+------+------+-----------+--------------------------------------+
| Server_id | Host | Port | Master_id | Slave_UUID                           |
+-----------+------+------+-----------+--------------------------------------+
|         2 |      | 3306 |         1 | 8cccc5f7-be7a-11ed-8855-000c29398d81 |
+-----------+------+------+-----------+--------------------------------------+
1 row in set (0.00 sec)

5. Verifique se a replicação mestre-escravo foi bem-sucedida

No servidor mestre, crie um banco de dados e tabelas:

root@(none) 20:16  mysql>create database db1;
Query OK, 1 row affected (0.00 sec)

root@(none) 20:19  mysql>use db1
Database changed
root@db1 20:19  mysql>create table t1(id int ,name varchar(20));
Query OK, 0 rows affected (0.01 sec)

root@db1 20:20  mysql> insert into t1 values(1,'lisi');
Query OK, 1 row affected (0.00 sec)

root@db1 20:20  mysql>select * from t1;
+------+------+
| id   | name |
+------+------+
|    1 | lisi |
+------+------+
1 row in set (0.00 sec)

Verifique se existe no servidor escravo:

root@(none) 20:16  mysql>use db1
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
root@db1 20:22  mysql>select * from t1;
+------+------+
| id   | name |
+------+------+
|    1 | lisi |
+------+------+
1 row in set (0.00 sec)

Acho que você gosta

Origin blog.csdn.net/zheng_long_/article/details/131773294
Recomendado
Clasificación