双主复制潜在的问题:

双主模型恰巧双方同时操作一组数据,左服务器锁住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