Experimento de replicación maestro-esclavo de MySQL


Preparación del experimento:

2 servidores MySQL:
maestro: 192.168.78.132
esclavo: 192.168.78.148

Principio de replicación maestro-esclavo

  1. Habilite el registro binario en el maestro
  2. Cuando los datos del maestro cambien, se generará un registro binario.
  3. El subproceso de volcado en el maestro notificará al subproceso io en el esclavo que obtenga el registro binario y luego lo escribirá en el registro de retransmisión del esclavo. Luego, el subproceso SQL leerá el registro de retransmisión recién generado y reproducirá las operaciones en el registro binario. logrando así que los datos del esclavo y del maestro sean exactamente iguales, manteniendo la coherencia.

1. Habilite los registros binarios

Habilite el registro binario en el servidor maestro,server_id=1

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

El registro binario también se puede habilitar en el servidor esclavo.server_id=2

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

2. Sincronizar los datos de la base de datos

Exporte el contenido de la base de datos del servidor maestro y luego impórtelo al servidor esclavo.

1.Exportar datos en 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. Importar datos al esclavo

Cargue el archivo de datos en el servidor esclavo e importe los datos para lograr datos iniciales consistentes en los servidores maestro y esclavo:
Operación en el servidor maestro:

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

Operación en el servidor esclavo:

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

3. Crea un nuevo usuario autorizado

Actualice MySQL en el servidor maestro para generar un nuevo registro para facilitar operaciones posteriores:

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)

Cree un nuevo usuario en MySQL en el servidor maestro:

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. Configurar en el servidor esclavo.

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 el estado del servidor esclavo:

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 el hilo 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

Resuelva el mismo problema con 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)

Simplemente modifique algunos caracteres, simplemente hágalo diferente de los del 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 resuelto con éxito:

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

Después del éxito, vea el archivo:

[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


¿Cómo sabe el Maestro qué servidores esclavos hay?

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 si la replicación maestro-esclavo es exitosa

En el servidor maestro, cree una base de datos y tablas:

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)

Compruebe si existe en el servidor esclavo:

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)

Supongo que te gusta

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