MySQL的主從與讀寫分離
阿新 • • 發佈:2018-12-26
1.環境準備(同時在兩臺虛擬機器上操作)
關閉防火牆
systemctl stop firewalld
setenforce 0
下載資料庫
yum -y install mariadb mariadb-server
開啟資料庫
systemctl start mariadb
說明
主資料庫 | 192.168.233.162 |
---|---|
從資料庫 | 192.168.233.163 |
配置主資料庫
1.用vi 開啟my.cnf
vi /etc/my.cnf
2.在[mysqld]標籤下面增加以下程式碼:
server-id=1 #主資料庫的id
log-bin=master-bin #日誌路徑,作用是從資料庫是根據這個日誌來複制主資料庫的資料的
重啟資料庫
systemctl restart mariadb
登入mariadb,授權遠端使用者(slaveuser為使用者名稱和密碼 “192.168.233.163”為從伺服器的地址,這裡需要改成自己伺服器的地址)
grant replication slave on *.* to 'slaveuser'@'192.168.233.163' identified by 'slaveuser';
flush privileges;
重啟mariadb服務
systemctl restart mariadb.service
配置從資料庫
1.用vi開啟my.cnf:
vi /etc/my.cnf
2.在[mysqld]標籤下面增加以下程式碼:
server-id=2 #這個id必須不能和主資料庫相同
read-only=on #設定該資料庫是隻讀狀態
relay-log=relay-bin #日誌
3.重啟mariadb服務
systemctl restart mariadb.service
在主伺服器的資料庫上查詢主服務狀態
SHOW MASTER STATUS;
進入從伺服器的資料庫:master_host需改為自己的主伺服器地址
change master to master_host='192.168.233.162',master_user='slaveuser',master_password='slaveuser', master_log_file='master-bin.000004',master_log_pos=245;
start slave; #重置slave 不重置有時候會出錯
START SLAVE;#啟動slave同步(在資料庫中)
show slave status\G 在slave伺服器上檢視slave同步的狀態
.檢視Slave_IO_Running和Slave_SQL_Running是否都為yes(一定要全部為yes。否則就是你配置錯了,再重新配置一遍從資料庫)