MySQL主從複製
主從複製:
通過日誌的方式將數據從MySQL主服務器(Master)經過網絡傳送到MySQL從服務器(Slave)上,然後重放。
準備:兩臺主機做MySQL服務器
172.16.75.1 Master
172.16.75.2 Slave
拓撲圖:
(一)配置:
Master:
[root@master ~]# vim /etc/my.cnf [mysqld] .... innodb_file_pertable=ON skip_name_resolve = ON log_bin=binlog server_id=199 sync_binlog=1 innodb_flush_log_at_trx_commit=1
開啓服務:
[root@master ~]# systemctl start mariadb
參數解釋:
innodb_file_pertable=ON:將每張表存儲在單獨的一個表文件中;
skip_name_resolve = ON :禁止域名解析(第一次建立連接時,IP和host name的映射關係已被緩存);
log_bin=binlog :開啓二進制日誌,日誌文件默認存放在/var/lib/mysql目錄下(路徑可自定義);
server_id=199 :數據庫服務器的ID ,不同的Mysql服務器ID設置爲不同值;
sync_binlog=1 :一旦二進制日誌文件有寫入操作時,立即將變化的數據同步到磁盤;
innodb_flush_log_at_trx_commit=1 :當有事務提交時,數據寫入二進制日誌文件中,並同步到磁盤;
Slave:
[root@s lave ~]# vim /etc/my.cnf [mysqld] ... innodb_file_per_table = ON skip_name_resolve = ON server_id=200 read_only=ON relay_log=slavelog
開啓服務:
[root@slave ~]# systemctl start mariadb
參數解釋:
read_only=ON :只讀
relay_log=slavelog :開啓事務日誌,作用:讀取並複製保存Master服務器的二進制日誌文件;
(二)將Master的數據內容全備份傳送到Slave,保持兩臺服務器數據一致
Master:
[root@master ~]# mysqldump --all-databases --lock-all-tables > alldb.sql [root@master ~]# scp alldb.sql [email protected]:/root/
Slave: 將Master端傳送來的數據進行重放
[root@slave ~]# mysql ... MariaDB [(none)]> \. alldb.sql
(三)
Master:
1. 授權一個用戶複製權限並設置密碼等;
2. 查看Master的狀態信息即(日誌文件和複製的位置)
MariaDB [(none)]> grant replication slave on *.* to 'west'@'172.16.%.%' identified by '111111'; Query OK, 0 rows affected (0.00 sec) MariaDB [(none)]> show master status ; +---------------+----------+--------------+------------------+ | File | Position| Binlog_Do_DB| Binlog_Ignore_DB| +---------------+----------+--------------+------------------+ | binlog.000009| 548 | | | +---------------+----------+--------------+------------------+ 1 row in set (0.00 sec)
Slave:指定Master_user, 密碼,端口,Master的二進制日誌文件,複製開始時Master二進制日誌文件的位置(從什麼位置開始複製):
MariaDB [(none)]> change master to master_host='172.16.75.1',master_user='west',master_password='111111',master_port=3306,master_log_file='binlog.000009',master_log_pos=548; Query OK, 0 rows affected (0.04 sec) MariaDB [(none)]> start slave; Query OK, 0 rows affected (0.01 sec)
查看Slave狀態:
如圖可看出Slave正在等待Master發送事件, Slave_IO_Running和Slave_SQL_Running兩個線程已開啓;
Slave_IO_Running作用:一旦Master二進制日誌文件有變化時,Slave讀取Master二進制日誌並複製到中繼日誌中;
Slave_SQL_Running作用:將中繼日誌中的內容重放;
測試:在Master端創建一個數據庫,並在Slave端檢測,看兩端是否一致;
Master:
MariaDB [(none)]> create database teachers;
Slave:
主從複製完成;