mysql 主從,主主,主主復制時的主鍵沖突解決


原理:slave 的i/o thread ,不斷的去master抓取 bin_log, 寫入到本地relay_log 然后sql thread不斷的更新slave的數據

 

 

把主服務器所有的數據復制給從服務器

 

 

slave_sql_running 主從的sql進程

slave_io_running 主從的io進程

seconds_behind_master 主從的數據延時

主從步驟

1.數據庫2邊同步,設置my.cnf

[mysqld]

log-bin=mysql-bin
binlog_format=mixed
server-id = 1
expire_logs_days = 10
log-bin=master-bin
log-bin-index=master-bin.index
binlog_ignore_db=mysql
binlog_ignore_db=infomation_schema
binlog_ignore_db=performance_schema

2.在master上建立mysql用戶,給slave用

created user 'ruser'@'%' indentified by 'ruserpwd'  建立用戶

grant replication slave on *.* to 'ruser'@'%' 用戶授權

第二種方法:grant replication client,replication slave on *.* to 'ruser'@'192.168.%.%' identified by '密碼123'

格式:grant 權限 on 數據庫.* to 用戶名@登錄主機 identified by “密碼”;

grant all privileges on *.* to 'root'@'%' identified by 'wangxiaohu';  所有權限

flush privileges

reset master; 清空master

reset slave; 清空slave

show master logs; 查看日志

show master status \G  查看master狀態,當前日志,及位置master_log_file,master_log_pos

3.從服務器my.ini 配置

 [mysqld]

server-id = 2
expire_logs_days = 10
relay-log-index=slave-relay-bin.index
relay-log=slave-relay-bin

slave 從服務器上登錄mysql運行change master 命令

show slave status \G 查看slave狀態

change master to 

MASTER_HOST='192.168.1.1'  ,

MASTER_USER='' , //主服務器的帳號

MASTER_PASSWORD='',

MASTER_PORT=3306,

 MASTER_LOG_FILE='mysql-bin.000001',

 MASTER_LOG_POS=0;

4.start slave;

 

主主復制時的主鍵沖突解決

設置my.cnf里面的2個參數auto_increment_increment,auto_increment_offset

讓1台服務器  1,3,5,7來增長

另1台服務器  2,4,6,8來增長

一台服務器:

set global auto_increment_increment = 2;  // 全局

set global auto_increment_offset = 1;

set session auto_increment_increment = 2; //當次連接

set session auto_increment_offset = 1;

 

另一台服務器:

set global auto_increment_increment = 2;

set global auto_increment_offset = 2;

set session auto_increment_increment=2;

set session auto_increment_offset = 2;

注:auto-increment-increment 和 auto-increment-offset 要寫到配置文件 中,防止下次重啟后失效.

有幾台服務器,auto_increment_increment就設置幾,比如3台服務器,auto_increment_increment=3,  3台服務器的auto_increment_offset依次開始為,1,2,3

備注:
log-slave-updates是為從庫的寫操作記錄binlog
多主互備和主從復制有一些區別,因為多主中的各個庫,都可以對服務器有寫權限,所以設計到自增長重復問題

可以看出,你的auto_increment字段在不同的服務器之間絕對不會重復,所以Master-Master結構就沒有任何問題了。當然,你還可以使用3台,4台,或者N台服務器,只要保證auto_increment_increment = N 再設置一下auto_increment_offset為適當的初始值就可以了,那樣,我們的MySQL可以同時有幾十台主服務器,而不會出現自增長ID重復。

在這里我們說的是2台MYSQL服務器,你也可以擴展到多台,實現方法類似
A -> B -> C-> D ->A
這樣一個環形的備份結構就形成了,最后可要記住 自增長ID(主鍵)要設計好哦,否則會出錯的。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM