一、主从复制的原理及工作过程
1、主从复制的原理
通过将MySQL的某一台主机(master)的数据复制到其他主机(slaves)上,并重新执行一遍来执行,复制过程中一台服务器充当主服务器,而其他一个或多个其他服务器充当从服务器。
2、主从复制的工作过程
1)MySQL将数据变化记录到二进制日志中;
2)Slave将MySQL的二进制日志拷贝到Slave的中继日志中;
3)Slave将中继日志中的事件在做一次,将数据变化,反应到自身(Slave)的数据库。
二、实验:主从同步配置
1、环境准备
准备三台没有配置过MySQL的主机:
|-------------|----------------|------|
| 主机名 | IP地址 | 主从架构 |
| openEuler-1 | 192.168.121.11 | 主 |
| openEuler-2 | 192.168.121.12 | 从 |
| openEuler-3 | 192.168.121.13 | 从 |
2、安装并配置MySQL
三台主机使用同一个安装MySQL方式:
# 这里以第一台主机为例
[root@openEuler-1 ~]# yum install -y mysql-server
# 启动服务(开机自启动)
[root@openEuler-1 ~]# systemctl enable --now mysqld
主库配置:
# 配置id(这里以ip地址作为编号),并开启gtid
[root@openEuler-1 ~]# vim /etc/my.cnf
[root@openEuler-1 ~]# tail -n3 /etc/my.cnf
server_id=11
gtid_mode=ON
enforce-gtid-consistency=ON
# 重启服务
[root@openEuler-1 ~]# systemctl restart mysqld
# 授权用户
[root@openEuler-1 ~]# mysql
mysql> create user rep@'192.168.121.%' identified with mysql_native_password by '123456';
mysql> grant replication slave on *.* to rep@'192.168.121.%';
从库配置:
# 从库1:
[root@openEuler-2 ~]# vim /etc/my.cnf
[root@openEuler-2 ~]# tail -n3 /etc/my.cnf
server_id=12
gtid_mode=ON
enforce-gtid-consistency=ON
[root@openEuler-2 ~]# systemctl restart mysqld
[root@openEuler-2 ~]# mysql
mysql> change replication source to
-> source_host='192.168.121.11',
-> source_user='rep',
-> source_password='123456',
-> source_auto_position=1;
mysql> start slave;
mysql> show slave status \G
# 从库2:
[root@openEuler-3 ~]# vim /etc/my.cnf
[root@openEuler-3 ~]# tail -n3 /etc/my.cnf
server_id=13
gtid_mode=ON
enforce-gtid-consistency=ON
[root@openEuler-3 ~]# systemctl restart mysqld
[root@openEuler-3 ~]# mysql
mysql> change replication source to
-> source_host='192.168.121.11',
-> source_user='rep',
-> source_password='123456',
-> source_auto_position=1;
mysql> start slave;
mysql> show slave status \G;
3、测试
在主库上建库建表插入数据:
mysql> create database db1;
Query OK, 1 row affected (0.02 sec)
mysql> use db1
Database changed
mysql> create table tb1(id int,name varchar(20));
Query OK, 0 rows affected (0.04 sec)
mysql> insert into tb1 values(1,'Jack'),(2,'Bob'),(3,'Zed');
Query OK, 3 rows affected (0.03 sec)
Records: 3 Duplicates: 0 Warnings: 0
mysql> select * from tb1;
+------+------+
| id | name |
+------+------+
| 1 | Jack |
| 2 | Bob |
| 3 | Zed |
+------+------+
3 rows in set (0.00 sec)
从库上查看:
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| db1 |
| information_schema |
| mysql |
| performance_schema |
| sys |
+--------------------+
5 rows in set (0.01 sec)
mysql> select * from db1.tb1;
+------+------+
| id | name |
+------+------+
| 1 | Jack |
| 2 | Bob |
| 3 | Zed |
+------+------+
3 rows in set (0.00 sec)