一. 配置my.cnf
master-1服务器中文件/etc/my.cnf 中添加如下配置:
# master
server-id=1 #server的唯一标识
auto_increment_offset=1 #自增id起始值
auto_increment_increment=2 #每次自增数字
log-bin = mysql-bin #打开二进制功能,MASTER主服务器必须打开此项
max_binlog_size=1024M #binlog单文件最大值
#slave-skip-errors=1062,1053,1146 #跳过指定error no类型的错误
slave-skip-errors=all
binlog-ignore-db = mysql,information_schema,performance_schema #不进行写入同步的库
#replicate-ignore-db = mysql #不进行读入同步的库
#replicate-ignore-db = information_schema
#replicate-ignore-db = performance_schema
#replicate-ignore-db = test
slave-1
# slave
server-id=2 #server的唯一标识
auto_increment_offset=1 #自增id起始值
auto_increment_increment=2 #每次自增数字
log-bin = mysql-bin #打开二进制功能,MASTER主服务器必须打开此项
max_binlog_size=1024M #binlog单文件最大值
#slave-skip-errors=1062,1053,1146 #跳过指定error no类型的错误
slave-skip-errors=all
binlog-ignore-db = mysql,information_schema,performance_schema #不进行写入同步的库
#replicate-ignore-db = mysql #不进行读入同步的库
#replicate-ignore-db = information_schema
#replicate-ignore-db = performance_schema
#replicate-ignore-db = test
配置完后,需重启mysql server
二. 添加同步账户
在需要同步数据的主节点添加账户:
grant replication slave on *.* to 'repl'@'192.168.1.102' identified by 'password';
三. 查看status
show master status;
查出来的字段 file 和 position,需记录,下一步需要.
四.设置同步
在slave节点执行sql,填写对应的值:
change master to master_host='MASTER_IP',master_port=3306,master_user='MASTER_USER',master_password='PASSWORD',master_log_file='mysql-bin.000005',master_log_pos=3123;
然后启动slave
start slave;
show slave status;
Slave_IO_Running: Yes
Slave_SQL_Running: Yes
都显示yes表示连接成功,然后测试新建数据库,表,数据是否正常.
同步前需要保持两库之间的库/表/数据已经一致. 如果不一致会出现同步失败,导致同步SQL线程结束,这时候需要重新设置position
stop slave;
change master to master_host='192.168.1.10',master_port=3306,master_user='slave',master_password='slave',master_log_file='mysql-bin.000003',master_log_pos=3393;
start slave;
从库一般是只读的,可以设置一下只读参数:
set global read_only=on #针对非超级管理员只读
set global super_read_only=on #所有用户只读