標籤:主主同步 雙主同步 mysql主主同步 mysql雙主同步
1. 兩台mysql都可以讀寫,互為主備,預設只是用一台(masterA)負責資料的寫入,另一台(masterB)備用;
2. masterA是masterB的主庫,masterB又是masterA的主庫,他們互為主從;
不足之處:
1. masterB可能處於抑制空閑狀態(可以用他當從庫,負責部分查詢);
2. 主庫後面提供服務的從庫要等masterB先同步完了資料後才能去masterB上去同步資料,肯能會造成一定程度的同步延遲;
搭建環境
系統:CentOS7
資料庫版本:5.6.36
masterA地址:192.168.188.2
masterB地址:192.168.188.3
安裝目錄:/usr/local/mysql/
資料目錄:/data/mysql/
A與B機器都安裝好了MySQL,資料庫與表都提前同步好;
防火牆配置iptables
添加mysql同學連接埠(預設3306)
vim /etc/sysconfig/iptables //編輯iptables檔案,也可以用iptables命令來添加,不過要儲存命令-A INPUT -m state --state NEW -m tcp -p tcp --dport 3306 -j ACCEPT //添加允許3306連接埠通過service iptables restart //重啟iptables服務
關閉selinux
vim /etc/selinux/config //編輯SELinux設定檔SELINUX=disabled //修改值為disabled為關閉
伺服器設定masterA設定(192.168.188.2)
vim /etc/my.cnf //編輯my.cnf檔案server-id=2 //增加server-id為2,一般為自己iplog_bin=test01 //設定log_bin名為test01
/etc/init.d/mysqld restart //重啟mysql服務
mysql -uroot -p123456 //登入mysql,不要照抄,-u後面是帳號,-p後面是密碼grant replication slave on *.* to ‘repl‘@‘192.168.188.3‘ identified by ‘123456‘; //建立mysql帳號repl,只容許指定ip訪問,也可以指定ip範圍192.168.188.%,其中%為萬用字元,表示所有;flush privileges; //重新整理授權表資訊flush tables with read lock; //鎖定資料庫表暫時無法寫服務;show master status; //查看binlog檔案值與pos值stop slave; //關閉同步
masterB設定(192.168.188.3)
vim /etc/my.cnfserver-id=3 //增加server-id為3,一般為自己iplog_bin=test02 //設定log_bin名為test02
/etc/init.d/mysqld restart //重啟mysql服務
mysql -uroot -p123456 //登入mysqlgrant replication slave on *.* to ‘repl‘@‘192.168.188.2‘ identified by ‘123456‘; //建立使用者,允許192.168.188.2登入本機器flush privileges; //重新整理授權表stop slave; //關閉同步show master status; //查看binlog檔案值與pos值
change master to master_host=‘192.168.188.2‘, master_user=‘repl‘, master_password=‘123456‘, master_log_file=‘test01.000001‘, master_log_pos=664383; //這裡注意log_file與pos值都要對應對應A的show master status;值start slave; //開啟同步
masterA設定
change master to master_host=‘192.168.188.3‘, master_user=‘repl‘, master_password=‘123456‘, master_log_file=‘test02.000001‘, master_log_pos=664343; //這裡log_file與pos值寫的必須是B上show master status;的值start slave; //開啟同步unlock tables; //解鎖寫
測試主主
在A的test資料庫下建立t1表,B上查詢後有t1表,證明B能同步A修改的資料;
在B的test資料庫下建立t2表,A上查詢,有t2表,證明A能同步到B修改後的資料;
masterA設定
mysql -uroot -p123456 //登入mysqlmysql> use test; //切換到資料庫test
mysql> show tables; //查看當前資料庫的所有表,這裡沒有一個表Empty set (0.00 sec)
mysql> create table t1(`id` int(4),`name` char(40)); //插入一個表t1mysql> show tables; //查看當前資料庫的表+----------------+| Tables_in_test |+----------------+| t1 |+----------------+1 row in set (0.00 sec)
masterB
mysql -uroot -p123456 //登入mysqluse test; //切換到資料庫testmysql> show tables; //查詢同步到資料庫test下出現了t1表,證明B能同步A的資料;+----------------+| Tables_in_test |+----------------+| t1 |+----------------+1 row in set (0.00 sec)
create table t2(`id` int(4),`name` char(40)); //建立一個t2表,如果A能同步到,就證明A能同步到B
切換masterA(省略了登入與切換資料庫的命令)
mysql> show tables; //查詢A的test資料庫下所有的表+----------------+| Tables_in_test |+----------------+| t1 || t2 |+----------------+2 rows in set (0.00 sec)
MySQL主主(雙主)資料同步