Skip to main content
Nordlys logo, a drawing of two gray mountains with green northern lights in the background 陈迪の自留地

Back to all posts

MySQL-5.7-主从同步配置

Published on by Chen Di · 2 min read

MySQL 安装

主从同步操作,版本为 5.7.44

yum install -y https://dev.mysql.com/get/mysql80-community-release-el7-3.noarch.rpm
yum list installed | grep mysql
yum repolist all | grep -E "mysql[0-9]+-community/x86"
yum-config-manager --disable mysql80-community
yum-config-manager --enable mysql57-community
rpm --import https://repo.mysql.com/RPM-GPG-KEY-mysql-2022
yum install -y mysql-community-server
systemctl start mysqld
systemctl status mysqld.service
grep 'temporary password' /var/log/mysqld.log

修改配置文件

主库配置文件

vim /etc/my.cnf

[mysqld]

log-bin=master-bin
binlog-format=ROW
server-id=1

从库配置文件

vim /etc/my.cnf

[mysqld]

log-bin=master-bin
binlog-format=ROW
server-id=2
read-only = 1

修改默认密码

mysql -uroot -p
alter user 'root'@'localhost' identified by 'anyWhere@2024'
flush privileges;

重启 MySQL

新建同步用户

create user 'tongbu'@'172.31.%' identified by 'anyWhere@2024';
grant replication slave on *.* to 'tongbu'@'172.31.%';

准备同步

如果不是新建的库,需要在同步前将主库数据导入从库。

在主库上执行以下命令导出数据库

mysqldump -uroot -p --all-databases --master-data > db_backup.sql

在从库上将 db_backup.sql 文件导入

mysql -uroot -p < db_backup.sql

配置主库连接信息

change master to master_host='172.31.12.203',master_user='tongbu',master_password='anyWhere@2024',master_log_file='master-bin.000001', master_log_pos=613;

# 在主库SHOW MASTER STATUS获取的File值
# 在主库SHOW MASTER STATUS获取的Position值

启动主从同步

START SLAVE;

可选操作——启用半同步复制

在主库上启用

SET GLOBAL rpl_semi_sync_master_enabled = 1;

在从库上启用

SET GLOBAL rpl_semi_sync_slave_enabled = 1;

检查复制状态

SHOW SLAVE STATUS\G;

确认以下两个状态为 Yes

  • Slave_IO_Running: Yes
  • Slave_SQL_Running: Yes