46、mysql雙主複製實戰
雙主複製潛在的問題:
雙主模型恰巧雙方同時操作一組資料,左伺服器鎖住A欄位修改B欄位,右伺服器鎖住B欄位修改A欄位。雙方一同步資料可能出現不一致。
1、在兩臺伺服器上各自建立一個具有複製許可權的使用者;
mysql
GRANT REPLICATION SLAVE,REPLICATION CLIENT ON *.* TO 'repluser'@'192.168.130.%' IDENTIFIED BY 'replpass';
FLUSH PRIVILEGES;
2、修改配置檔案;
主伺服器A上
service mysqld stop
vim /etc/my.cnf
[mysqld]
server-id = 10
log-bin=/mydata/binlog/log-bin
relay-log = /mydata/relaylog/relay-log
auto-increment-offset = 1
auto-increment-increment = 2
skip-slave-start
service mysqld start
主伺服器B上
service mysqld stop
vim /etc/my.cnf
[mysqld]
server-id = 20
log-bin=/mydata/binlog/log-bin
relay-log = /mydata/relaylog/relay-log
auto-increment-offset = 2
auto-increment-increment = 2
skip-slave-start
service mysqld start
3、如果此時兩臺伺服器均為新建立,且無其它寫入操作,各伺服器只需記錄當前自己二進位制日誌檔案及事件位置,以之作為另外的伺服器複製起始位置即可
主伺服器A上
MariaDB [(none)]> SHOW MASTER STATUS \G;
*************************** 1. row ***************************
File: log-bin.000001
Position: 682
Binlog_Do_DB:
Binlog_Ignore_DB:
1 row in set (0.00 sec)
主伺服器B上
MariaDB [(none)]> SHOW MASTER STATUS \G;
*************************** 1. row ***************************
File: log-bin.000001
Position: 682
Binlog_Do_DB:
Binlog_Ignore_DB:
1 row in set (0.00 sec)
4、各伺服器接下來指定對另一臺伺服器為自己的主伺服器即可:
主伺服器A上
CHANGE MASTER TO MASTER_HOST = '192.168.130.62', MASTER_USER='repluser', MASTER_PASSWORD='replpass',MASTER_LOG_FILE='log-bin.000001', MASTER_LOG_POS=682;
START SLAVE;
SHOW SLAVE STATUS\G;
主伺服器B上
CHANGE MASTER TO MASTER_HOST = '192.168.130.61', MASTER_USER='repluser', MASTER_PASSWORD='replpass',MASTER_LOG_FILE='log-bin.000001', MASTER_LOG_POS=682;
START SLAVE;
SHOW SLAVE STATUS\G;
5、各伺服器寫入資料測試
主伺服器A上
CREATE DATABASE testdb;
USE testdb;
CREATE TABLE t1 (ID TINYINT NOT NULL AUTO_INCREMENT PRIMARY KEY,Name VARCHAR(50) NOT NULL);
INSERT INTO t1 (Name) VALUES ('A1'),('A2');
MariaDB [testdb]> SELECT * FROM t1;
+----+------+
| ID | Name |
+----+------+
| 1 | A1 |
| 3 | A2 |
+----+------+
2 rows in set (0.00 sec)
主伺服器B上
USE testdb;
INSERT INTO t1 (Name) VALUES ('B1'),('B2');
MariaDB [testdb]> SELECT * FROM t1;
+----+------+
| ID | Name |
+----+------+
| 1 | A1 |
| 3 | A2 |
| 4 | B1 |
| 6 | B2 |
+----+------+
4 rows in set (0.00 sec)
多主,且高可用的解決方案
MMM:Multi Master MySQL
MHA:MySQL HA