Mysql 主从设置

注:5.6 之后建议使用 GTIDs 方式同步

主数据库相关操作

主数据库配置文件

1
2
3
4
5
# my.cnf配置文件
[mysqld]
log-bin=mysql-bin
binlog_format=row
server-id = 1

创建一个用户用于同步

1
2
3
4
5
# 创建 用户
create user 'username'@'host' identified by 'password'

# 授权
grant replication salve on *.* to 'username'@'host'

获取同步点

1
2
3
4
5
6
7
# 给表加只读锁,防止写入操作
FLUSH TABLES WITH READ LOCK;
# 查看主库状态
SHOW MASTER STATUS;

# 设置为读写状态,slave 数据库开启同步后执行此操作
unlock tables;

只读模式开启和关闭

1
2
3
4
5
6
7
8
9
# 设置为只读
show global variables like "%read_only%";
flush tables with read lock;
set global read_only=1;
show global variables like "%read_only%";

# 设置为读写状态
unlock tables;
set global read_only=0;

导入数据

从数据库相关操作

创建

1
2
3
4
5
6
7
mysql> CHANGE MASTER TO
-> MASTER_HOST='master_host_name',
-> MASTER_USER='replication_user_name',
-> MASTER_PORT=16300
-> MASTER_PASSWORD='replication_password',
-> MASTER_LOG_FILE='recorded_log_file_name',
-> MASTER_LOG_POS=recorded_log_position;

状态查看

1
2
3
4
5
6
# 启动
START SLAVE;
# 关闭
stop slave
# 查看状态
show slave status\g;

参考

[主从说明]https://dev.mysql.com/doc/refman/5.7/en/replication-howto.html