主从原理:MySQL 主从同步是一种数据库复制技术,它通过将主服务器上的数据更改复制到一个或多个从服务器,实现数据的自动同步。
主从同步的核心原理是将主服务器上的二进制日志复制到从服务器,并在从服务器上执行这些日志中的操作。
主要基于MySQL二进制日志 主要包括三个线程(2个I/O线程,1个SQL线程)

1、MySQL将数据变化记录到二进制日志中;
2、Slave将MySQL的二进制日志拷贝到Slave的中继日志中;
3、Slave将中继日志中的事件在做一次,将数据变化,反应到自身(Slave)的数据库
详细步骤:
1、从库通过手工执行change master to 语句连接主库,提供了连接的用户一切条件(user 、password、port、ip),并且让从库知道,二进制日志的起点位置(file名 position 号); start slave
2、从库的IO线程和主库的dump线程建立连接。
3、从库根据change master to 语句提供的file名和position号,IO线程向主库发起binlog的请求。
4、主库dump线程根据从库的请求,将本地binlog以events的方式发给从库IO线程。
5、从库IO线程接收binlog events,并存放到本地relay-log中,传送过来的信息,会记录到master.info中
6、从库SQL线程应用relay-log,并且把应用过的记录到relay-log.info中,默认情况下,已经应用过的relay 会自动被清理purge

本实验需要用到三台虚拟机
首先在三台虚拟机上分别:yum install -y mysql-server
方法一:基于binlog的主从同步
主库配置(虚拟机1):
vim /etc/my.cnf 写入
server_id=11

启动服务:systemctl start mysqld
设置开机自启:systemctl enable mysqld --now
mysql> create user rep@'192.168.234.%' identified with mysql_native_password by '123456';
#identified with mysql_native_password
表示使用 mysql_native_password
认证插件来验证用户的身份。
mysql> grant replication slave on *.* to rep@'192.168.234.%'; #赋予权限

++注意:show master status
是设置和维护 MySQL 主从复制的重要命令,它提供了从服务器所需的二进制日志的关键信息,帮助实现主从服务器之间的数据同步。++
++从库配置(虚拟机2):++
++vim /etc/my.cnf写入++

启动服务:systemctl start mysqld
设置开机自启:systemctl enable mysqld --now

mysql> start slave;启动从服务器

虚拟机2主从配置成功!
++从库配置(虚拟机3):++
++vim /etc/my.cnf写入++

启动服务:systemctl start mysqld
设置开机自启:systemctl enable mysqld --now
跟上面一样的配置

mysql> start slave;启动从服务器

虚拟机3主从配置成功!
验证:
在主服务器(虚拟机1)上创建一个新的数据库,新的数据表
mysql> create database db1;
mysql> use db1;
mysql> create table t1(id int,name varchar(10));
mysql> insert into t1 values(1,'zhangsan'), (2,'lisi');
在从服务器(虚拟机2,虚拟机3)上查看是否同步

验证成功!
**方法二:**基于gtid的主从同步配置
主服务器(虚拟机1):
vim /etc/my.cnf写入

systemctl restart mysqld.service
从服务器·(虚拟机2):

systemctl restart mysqld.service
mysql> stop slave; #停止slave服务·

mysql> start slave;

主从配置成功!
从服务器·(虚拟机3):

systemctl restart mysqld.service
mysql> stop slave;

mysql> start slave;

主从配置成功!
验证:
在主服务器(虚拟机1)上创建一个新的数据库,新的数据表
mysql> create database db2;
mysql> use db2;mysql> create table t2(id int,name varchar(20),year int);
mysql> insert into t2 values(1,'zhangsan',16), (2,'lisi',17),(3,'wangwu',18);
在从服务器(虚拟机2,虚拟机3)上查看是否同步
