概述
MySQL主從備份配置的原理是Master更新寫入二進制日志文件虹钮,并維護日志文件的索引聋庵。Slave從二進制文件讀取更新內容,在Slave上重新執(zhí)行一遍來進行備份芙粱。
表的更新需要在Master上進行祭玉,否則可能會出現(xiàn)Master和Slave更新沖突。
環(huán)境
- CentOS 7.0
- MySQL5.7.10
- Master Host IP : 10.16.13.128
- Slave Host IP : 10.16.13.129
- MySQL同步賬戶:-u username -p password
配置過程
1. 分別在主從服務器上安裝MySQL,最好版本相同宅倒。
2. 修改Master上MySQL配置文件my.cnf
[mysqld]
log-bin=mysql-bin // [必須]啟用二進制日志
server-id=1 // [必須]服務器唯一ID
3. 修改Slave上MySQL配置文件my.cnf
[mysqld]
log-bin=mysql-bin // [非必須]Slave可以不啟用二進制日志攘宙,配置二進制日志可以便于Master和Slave交換角色
server-id=2 // [必須]服務器唯一ID
4. 重啟Master和Slave上的MySQL
5. 在Master上使用root用戶登錄建立同步賬戶并授權Slave
mysql> GRANT REPLICATION SLAVE ON *.* to 'username'@'%' identified by 'password';
mysql> FLUSH PRIVILEGES;
6. 使用root賬戶登錄Master查看Master狀態(tài)
mysql> show master status;
+------------------+----------+--------------+------------------+-------------------+
| File | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set |
+------------------+----------+--------------+------------------+-------------------+
| mysql-bin.000002 | 6584 | thisonedb | mysql | |
+------------------+----------+--------------+------------------+-------------------+
7. 配置Slave跟蹤Master日志的位置
mysql> change master to master_host='10.16.13.128',master_user='username',master_password='q123456',master_log_file='mysql-bin.000002',master_log_pos=6584;
mysql> start slave;
8. 使用root賬戶登錄MySQL核對Slave狀態(tài)
mysql> show slave status\G;
*************************** 1. row ***************************
Slave_IO_State: Waiting for master to send event
Master_Host: 10.16.13.128
Master_User: username
Master_Port: 3306
Connect_Retry: 60
Master_Log_File: mysql-bin.000002
Read_Master_Log_Pos: 6584
Relay_Log_File: bx-13-129-relay-bin.000003
Relay_Log_Pos: 6797
Relay_Master_Log_File: mysql-bin.000002
Slave_IO_Running: Yes
Slave_SQL_Running: Yes
需要特別核對Slave_IO_State、Slave_IO_Running拐迁、Slave_SQL_Running 值蹭劈,以上值為正確配置狀態(tài)。
9. 檢查主從備份是否配置成功线召,在Master上創(chuàng)建Table或插入數(shù)據(jù)铺韧,查看Slave數(shù)據(jù)是否與Master同步
10. 用crontab設置定期任務執(zhí)行腳本檢查Slave狀態(tài)
# !/bin/bash
array=($(mysql -uroot -p -e "show slave status\G" | grep "Running" | awk '{print $2}'))
if [ "${array[0]}" == "Yes" ] || [ "${array[1]}" == "Yes" ]
then
echo "Slave is OK"
else
echo "Slave is error"
fi