一、MySQL主从复制的原理
1、mysql的复制过程:每执行一个写操作,它都会往自己的数据库中存一份,与此同时这个写操作也会存储在二进制日志文件中一份,并且把它们保存为事件,所以在这个数据库上,前端数据每执行一个写操作或者有可能引起修改的操作,都会保存一个事件,我们就把这个事件通过mysql服务器3306端口发送给另外一台服务器,另外一台服务器把这个事件接收下来,接受下来以后先保存在本地的日志文件中,而后从这个日志文件中一次读一个事件并且在本地执行一下,然后保存在数据库里面,这个过程就叫mysql的复制。如下图所示:
2、在这样一个模型当中,我们把允许来自外部操作记录下来记录到数据库中,并保存至二进制文件中的这台服务器叫做复制架构中主服务器(master)。主服务器中的日志文件叫二进制日志。
3、slave:从服务器中的日志文件是从主服务器中复制过来的,叫做中继日志,主要目的是复制下来,再在本地用一遍,相当于产生一个接力的过程。
4、主服务器允许并行执行,主服务器上若有多个CPU,它允许多个服务器并行执行。但是我们写到二进制文件中,只能一条一条的写,从服务器只能一条一条的执行。从服务器默认情况下也只能是一个进程,读一条执行一个,所以从服务器慢于主服务器。
二、准备三台虚拟机192.168.1.11 198.168.1.12 198.168.1.13(要关闭防火墙)
选取192.168.1.11作为主机
vim /etc/my.cnf
grant replication slave on *.* to rep@'192.168.1.%';
启动
systemctl enable --now mysqld.service
在主库里授权一个用户
create user rep@'192.168.1.%' identified with mysql_native_password by '123456';
查看binlog文件名
show master status;
接着配置另外两个从库
vim /etc/my.cnf
#
# This group is read both both by the client and the server
# use it for options that affect everything
#
[client-server]
#
# This group is read by the server
#
[mysqld]
server_id=11
#
# include all files from the config directory
#
!includedir /etc/my.cnf.d
#
# This group is read both both by the client and the server
# use it for options that affect everything
#
[client-server]
#
# This group is read by the server
#
[mysqld]
server_id=12
#
# include all files from the config directory
#
!includedir /etc/my.cnf.d
接着启动
systemctl enable --now mysqld.service
查看状态
show slave status \G
*************************** 1. row ***************************
Slave_IO_State: Waiting for source to send event
Master_Host: 192.168.1.11
Master_User: rep
Master_Port: 3306
Connect_Retry: 60
Master_Log_File: binlog.000001
Read_Master_Log_Pos: 678
Relay_Log_File: localhost-relay-bin.000002
Relay_Log_Pos: 323
Relay_Master_Log_File: binlog.000001
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: 678
Relay_Log_Space: 537
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: 11
Master_UUID: 3928f497-d672-11ef-8e26-000c294d2ac6
Master_Info_File: mysql.slave_master_info
SQL_Delay: 0
SQL_Remaining_Delay: NULL
Slave_SQL_Running_State: Replica 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:
Master_public_key_path:
Get_master_public_key: 0
Network_Namespace:
1 row in set, 1 warning (0.00 sec)
连接成功