本文配置主从使用的操作系统是Centos7,数据库版本是mysql5.7。

准备好两台安装有mysql的机器(mysql安装教程链接

主数据库配置

每个从数据库会使用一个MySQL账号来连接主数据库,所以我们要在主数据库里创建一个账号,并且该账号要授予 REPLICATION SLAVE 权限

创建一个同步账号

create user 'repl'@'%' identified by 'repl_Pass1';

授予REPLICATION SLAVE权限:

GRANT REPLICATION SLAVE ON *.* TO 'repl'@'%';

要配置主数据库,必须要启用二进制日志,并且创建一个唯一的Server ID,打开mysql的配置文件并编辑(位置/etc/my.cnf),增加如下内容

log_bin=master-bin
log_bin_index = master-bin.index
server-id=4
expire-logs-days=7
binlog_ignore_db=mysql
binlog_ignore_db=information_schema
binlog_ignore_db=performation_schema
binlog_ignore_db=sys
binlog_do_db=mybatis
log_bin=master-bin 启动MySQL二进制日志
log_bin_index = master-bin.index
server-id=4  服务器唯一标识
expire-logs-days=7 二进制日志的有效期
binlog_ignore_db=mysql 不需要同步的数据库
binlog_ignore_db=information_schema
binlog_ignore_db=performation_schema
binlog_ignore_db=sys
binlog_do_db=mybatis 需要同步的数据库名字

CentOS7下Mysql5.7主从数据库配置-LMLPHP

重启mysql服务,查看主服务器状态:

show master status;

CentOS7下Mysql5.7主从数据库配置-LMLPHP

注意将方框里的两个值记录下来,后面在配置从数据库的时候用到。

 从数据库配置

同样编辑配置文件my.cnf,插入如下内容

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

CentOS7下Mysql5.7主从数据库配置-LMLPHP

重启mysql服务,在slave服务器中登陆mysql,连接master主服务器数据库(参数根据实际填写)

change master to master_host='192.168.134.10', master_port=3306, master_user='repl', master_password='repl_Pass1', master_log_file='master-bin.000001', master_log_pos=2237;

启动slave

start slave;

测试主从是否配置成功

主从同步的前提必须是两个数据库都存在,本案例中我们需要建好两个名为mybatis的数据库

主库创建一个表

CentOS7下Mysql5.7主从数据库配置-LMLPHP

发现从库也创建了相同的表,然后发现主库的增删改操作都会自动同步。

10-07 16:37