MySQL主从复制
注:配置主从复制主机要先关闭iptables(iptables -F)。关闭之后使用mysql -uslave -hIP -ppassword 试一下能不能连接主库成功
实现原理
mysql支持单向、异步复制,复制过程中一个服务器充当主服务器,而一个或多个其它服务器充当从服务器
mysql复制基于主服务器在二进制日志中跟踪所有对数据库的更改(更新、删除等)
每个从服务器接收主服务器已经记录到其二进制日志的保存更新
实现步骤
Master将改变记录到二进制日志(binary log)中
Slave将Master的binary log enents 拷贝到它的中继日志(relay log)
Slave执行中继日志中的事件,将改变相应它自己的数据
配置主机
set global validate_password_policy=0;
vim /etc/my.cnf
添加如下内容
log-bin=mysql-bin
server-id=129 #唯一
cd /var/lib/mysql
出现mysql-bin.000001文件
主库设置成功
mysql> show master status;
+—————————+—————+———————+—————————+—————————-+
| File | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set |
+—————————+—————+———————+—————————+—————————-+
| mysql-bin.000001 | 154 | | | |
+—————————+—————+———————+—————————+—————————-+
1 row in set (0.00 sec)
记住mysql-bin.000001这个日志文件
主机授权从机监听日志grant replication slave on *.* to [email protected].130 identified by 'password';
配置从机
vim /etc/my.cnf
添加以下内容
server-id = 130 #唯一
relay_log = mysql-relay-bin
mysql> stop slave;
Query OK, 0 rows affected, 1 warning (0.00 sec)
mysql> change master to
-> master_host='192.168.153.129', #主机IP
-> master_port=3306,#端口
-> master_user='slave',
-> master_password='password',
-> master_log_file='mysql-bin.000001',#主机日志文件
-> master_log_pos=452;
Query OK, 0 rows affected, 2 warnings (0.02 sec)
mysql> start slave;
Query OK, 0 rows affected (0.01 sec)
mysql> show slave status\G
*************************** 1. row ***************************
Slave_IO_State: Waiting for master to send event
Master_Host: 192.168.153.129
Master_User: slave
Master_Port: 3306
Connect_Retry: 60
Master_Log_File: mysql-bin.000001
Read_Master_Log_Pos: 452
Relay_Log_File: mysql-relay-bin.000002
Relay_Log_Pos: 320
Relay_Master_Log_File: mysql-bin.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: 452
Relay_Log_Space: 527
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: 129
Master_UUID: 406cb9ad-c33a-11e7-b1ff-000c29ded369
Master_Info_File: /var/lib/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:
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)
主从复制配置成功