在Centos7配置MySQL主从同步

本次配置使用的服务器

master 192.168.3.30
salve 192.168.3.31

Master配置

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

加入以下配置

1
2
3
bind-address = 192.168.33.22 #your master ip 开启访问权限
server-id = 1 #在master-slave架构中,每台机器节点都需要有唯一的server-id
log-bin=mysql-bin

重启mysql
/etc/init.d/mysqld restart

创建主从同步的mysql user (在Mysql命令行操作)

CREATE USER ‘slave1’@‘192.168.3.31’ IDENTIFIED BY ‘slave1’;
赋权
GRANT REPLICATION SLAVE ON . TO ‘slave1’@‘192.168.3.31’;

为了保证主从数据库数据同步,暂时加入读锁,防止数据同步时期数据变动导致主从不一致
FLUSH TABLES WITH READ LOCK;

记录下来MASTER REPLICATION LOG 的位置

1
2
3
4
5
6
7
mysql> SHOW MASTER STATUS;
+------------------+----------+--------------+------------------+-------------------+
| File | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set |
+------------------+----------+--------------+------------------+-------------------+
| mysql-bin.000001 | 120 | | | |
+------------------+----------+--------------+------------------+-------------------+
1 row in set (0.00 sec)

导出主库数据
mysqldump -u root -p --all-databases --master-data > dbdump.sql
发现mysqldump 命令不存在
ln -s /usr/local/mysql/bin/mysqldump /usr/bin/mysqldump
加入链接

解除读锁
UNLOCK TABLES;

将导出文件传输到salve
scp dbdump.sql root@192.168.3.31:/root/

Salve配置

更改/etc/my.cnf配置文件

1
2
3
bind-address = 192.168.3.30 # 授权访问地址
server-id = 2 #master-slave结构中,唯一的server-id
log_bin = mysql-bin

重启mysql是配置生效
/etc/init.d/mysqld restart

导入数据

mysql -u root -p < /root/dbdump.sql

使slave与master建立连接,从而同步

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
stop slave; # 先停止

启动
CHANGE MASTER TO
MASTER_HOST='192.168.3.30', # 主库IP
MASTER_USER='slave1', # 主库用户名
MASTER_PASSWORD='slave1',# 主库密码
MASTER_LOG_FILE='mysql-bin.000003',
MASTER_LOG_POS=333;
后面两项可以在主库中使用`show master status`命令查看

>mysql> show master status;
>+------------------+----------+--------------+------------------+-------------------+
>| File | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set |
>+------------------+----------+--------------+------------------+-------------------+
>| mysql-bin.000003 | 333 | | | |
>+------------------+----------+--------------+------------------+-------------------+

start slave ; # 启动同步

到这里应该已经可以同步了,如果不行,在从库使用show slave status\G 查看详细原因
主要查看 Slave_IO_Running: Yes Slave_SQL_Running: Yes两项