Mysql主主同步配置方法

来源:互联网 发布:网络病毒营销的前提 编辑:程序博客网 时间:2024/04/29 07:28

环境

服务器a:172.16.0.123
服务器b:172.16.0.132
Mysql版本:5.6.22
System OS:CentOS release 6.3

创建同步用户

服务器a和b分别建立一个同步用户:
mysql> grant replication slave on . to ‘hello’@’172.16.0.%’ identified by ‘world’;
mysql>flush privileges;

修改mysql配置文件/etc/my.cnf

服务器a

[mysqld]
server-id = 1
log-bin=mysql-bin
binlog-do-db = helloworld
binlog-ignore-db=mysql

log-slave-updates
sync_binlog=1
auto_increment_offset=1
auto_increment_increment=2
replicate-do-db = helloworld
replicate-ignore-db = mysql,information_schema

服务器b

[mysqld]
server-id = 2
log-bin = mysql-bin
replicate-do-db = helloworld
replicate-ignore-db = mysql,information_schema

binlog-do-db = helloworld
binlog-ignore-db=mysql
log-slave-updates
sync_binlog=1
auto_increment_offset=2
auto_increment_increment=2

保存之后分别重启a、b上的mysql服务:
service mysql restart

注意:

1.一定要区分[mysqld] 和[mysql],如果眼花不小心在[mysql]里写就会出现:
[root@XXXX etc]# mysql
mysql: unknown variable ‘server-id=1’

2.由于两台主机的地位是一样的,都可以写入数据,所以很可能会出现主键的数据冲突。比如我们建表的时候ID是使用自增的主键,如果两台主机都同时写入ID=1的数据那就冲突了。这里采用了简单的避免冲突的方法,用auto_increment_increment来控制列中的值的增量值,用auto_increment_offset来确定AUTO_INCREMENT列值的起始偏移位置:
服务器a以1、3、5、7的方式增长
服务器b以2、4、6、8的方式增长

指定同步位置

查看服务器a作为主服务器时的状态:
mysql> show master status\G
***************** 1. row *****************
File: mysql-bin.000329
Position: 120
Binlog_Do_DB: helloworld
Binlog_Ignore_DB: mysql
1 row in set (0.00 sec)

b服务器上:
mysql>change master to master_host=’172.16.0.123, master_user=’hello’, master_password=’world’, master_log_file=’mysql-bin.000329’, master_log_pos=120;

指定前先执行
mysql>stop slave;
确保线程不在运行状态

然后以同样的方法设置在a服务器上指定b服务器的同步位置
接着分别在服务器a、b上启动服务器线程:
mysql>start slave;

查看服务器a、b的从服务器状态:
mysql> show slave status\G
***************** 1. row *****************
Slave_IO_State: Waiting for master to send event
Master_Host: 172.16.0.123
Master_User: hello
Master_Port: 3306
Connect_Retry: 60
Master_Log_File: mysql-bin.000329
Read_Master_Log_Pos: 120
Relay_Log_File: mysql-relay-bin.000001
Relay_Log_Pos: 4
Relay_Master_Log_File: mysql-bin.000329
Slave_IO_Running: Yes
Slave_SQL_Running: Yes
Replicate_Do_DB: helloworld
Replicate_Ignore_DB: mysql

1 row in set (0.00 sec)

其中
Slave_IO_Running: Yes
Slave_SQL_Running: Yes
表示状态正常

注意:

1.如果Slave_IO_Running: No 则需要检查change master语句中的log位置和配置的log位置是否一样,还有log文件名是否一致。

2.在show master status\G 之前可以加锁来保证数据不被别人操作 flush tables with read lock;指定完同步位置之后再用unlock tables;来解锁

0 0
原创粉丝点击