mysql主從原理:mysql
1)至少須要2臺數據庫服務器,一主一從,master開啓bin-log功能。(bin-log功能用戶記錄主控增 加、刪除、修改、更新SQL的語句。) sql
2)異步複製的過程,有延遲,毫秒級別(延遲和你的網絡和性能、數據庫的量級有關),開啓3個線程。分別是master開啓io線程,slave開啓io線程、sql線程。數據庫
3)從庫啓動 salve start,經過io線程、用戶名和密碼去鏈接master,master接收請求後,master io線程負責將bin-log內容position位置點數據發給salve端。服務器
4)slave io線程收到數據以後,會將內容追加到本地relay-log中繼日誌,同時會產生master.info文件(此次從哪臺機器同步,用戶名、密碼、bin-log文件名、position位置).網絡
5)slave SQL線程實時監測relay-log,若是這個日誌內容有更新,解析文件中的SQL語句,在本地去執行。異步
實戰:ide
1)master配置文件中開啓bin-log,設置server-id性能
2)受權同步用戶和密碼測試
3)slave執行change master綁定主庫url
192.168.1.155(master)
192.168.1.156(salve)
注:關掉服務器的防火牆和setenforce 0
主庫配置:
1.在mysql配置文件中加入
log-bin=mysql-bin(開啓bin-log)
server-id=1(區分主從)
2.重啓數據庫
/etc/init.d/mysql restart
3.進入數據庫,建立一個新的用戶,並受權容許同步
create user 'tongbu'@'192.168.1.156' identified by '123456';(建立用戶)
grant replication slave on *.* to 'tongbu'@'192.168.1.156' identified by '123456';(受權給從庫)
4.查看主庫狀態
mysql> show master status;
+------------------+----------+--------------+------------------+-------------------+
| File | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set |
+------------------+----------+--------------+------------------+-------------------+
| mysql-bin.000001 | 990 | | | |
+------------------+----------+--------------+------------------+-------------------+
1 row in set (0.01 sec)
從庫配置:
5.修改從庫配置文件
server-id = 2
6.重啓數據庫
/etc/init.d/mysql restart
7.在從服務器上指定master IP和同步的pos點
進入數據庫:
change master to master_host='192.168.1.155' ,master_user='tongbu' ,master_password='123456' ,master_log_file='mysql-bin.000001' ,master_log_pos=990;
注:若是報錯
ERROR 3021 (HY000): This operation cannot be performed with a running slave io thread; run STOP SLAVE IO_THREAD FOR CHANNEL '' first
說明slave正在運行,stop slave;(關閉slave)
7.啓動slave
start slave;
8.測試,在主庫建立一個數據庫,查看從庫是否同步過來。
(本實驗是成功的)