1) A , B 兩台 mysql 服務器
一、服務器參數,編輯 /etc/my.cnf
[A 服務器 ]
server-id = 1
binlog-do-db = test
binlog-ignore-db = mysql
replicate-do-db = test
replicate-ignore-db = mysql
master-host = 192.168.255.195
master-user = repl
master-password = repl
master-port = 3306
master-connect-retry = 10
sync-binlog = 1
log-bin=mysql-bin
[B 服務器 ]
server-id = 2
binlog-do-db = test
binlog-ignore-db = mysql
replicate-do-db = test
replicate-ignore-db = mysql
master-host = 192.168.255.194
master-user = repl
master-password = repl
master-port = 3306
master-connect-retry = 10
sync-binlog = 1
log-bin=mysql-bin
2) 在 A 和 B 上進行數據庫操作
A/B: Slave stop;
A/B: Reset master;
A: grant replication slave on *.* to [email protected] identified by 'repl';
B: grant replication slave on *.* to [email protected] identified by 'repl';
A/B: show master status;
A: change master to master_host='192.168.255.194',master_user='repl',master_password='repl',master_port=3306,master_log_file='mysql-bin.000001',master_log_pos=98;(log 根據 master status)
B:
change master to master_host='192.168.255.195',master_user='repl',master_password='repl',master_port=3306,master_log_file='mysql-bin.000006',master_log_pos=98; (log 根據 master status)
A/B: slave start;
A/B: show slave status\G;( 查看同步狀態 )
看到如下狀態就表示同步成功
Slave_IO_Running: Yes
Slave_SQL_Running: Yes
Seconds_Behind_Master: 0
3) 測試數據庫同步,在 A 的 test 庫裡增加表,在 B 的 test 庫裡刪除表
Use test ;
A:Create table username (id int(15));
查看 B 中是否有 username 這個表
B: drop table username
查看 A 中是否已經刪除 usernam 這個表
A/B : show slave status\G;( 再次查看同步狀態,如果沒問題就表示成功 )
4) 互為同步配置實例
1. A B 互為主從同步 test, 不同步 mysql :
兩個數據庫配置中均設置: binlog-do-db=test, binlog-ignore-db=mysql , replicate-do-db=test , replicate-ignore-db=mysql
2. A B 互為主從只同步 test ,不同步其他數據庫,新創建的也不會同步
兩個數據庫配置中均設置: binlog-do-db=test , replicate-do-db=test
3. A B 互為主從不同步 mysql, 同步其他數據庫,譬如創建的新數據庫也會同步
兩個數據庫配置中均設置: binlog-ignore-db=mysql , replicate-ignore-db=mysql
4. A B 互為主從同步所有數據庫,包括新建的數據庫
兩個數據庫配置中均不設置上述四項
5) 實現自動同步的 shell 腳本
1. 增加 super 和 replication client on 權限
grant super on *.* to [email protected] identified by 'repl';
grant replication client on *.* to [email protected] identified by 'repl';
2. 自動同步腳本 autosync.sh
#!/bin/bash
while true
do
status=`/usr/bin/mysql -uroot -e "show slave status\G;"|grep Slave_SQL_Running|cut -f2 -d":"|sed 's/ //'`
if [ $status != "Yes" ]
then
A=`/usr/bin/mysql -urepl -prepl -h192.168.255.194 -e "show master status"|grep mysql-bin|awk '{print $2}'`
/usr/bin/mysql -uroot -e "slave stop"
/usr/bin/mysql -uroot -e "change master to master_host='192.168.255.194',master_user='repl',master_password='repl',master_port=3306,
master_log_file='mysql-bin.000001',master_log_pos=$A"
/usr/bin/mysql -uroot -e "slave start"
fi
sleep 10
done
3. 後台執行
nohup ./autosync.sh >/dev/null 2>&1 &
作者“duanjiangong”