MySQL 主从复制 - binary log

MySQL 主从复制 - binary log

原理

网上找的,图源水印

主要流程

主服务器设置:

  • 创建复制账号并授予复制权限
  • 获取 binary log 状态。

从服务器设置:

  • 设置主服务器信息。
  • 启动并检查复制服务。

提示

出于“政治正确”,MySQL 对“主从(仆)”这对词进行了替换,所以导致部分流程出现了差异。其实自 8.0.22 开始,slave 基本都被替换为了 replica。但是像 GRANT 授权语句里的直到 MySQL 9 都没被替换。

本文用到 MySQL 版本:

  • MySQL 9.0/8.4 for docker(对本文来说无区别)
  • MySQL 8.0.34 for docker

主服务器详细步骤

创建复制账号授予同步权限

首先创建复制用的账号,专号专用比较好。管理员登陆 MySQL,执行:

creat user 'repl'@'%' identified by 'password';

这里假设用户名为repl,密码为password,使用时请替换为实际的用户名和密码。

授予该用户同步权限:

grant replication slave on *.* TO 'repl'@'%';

获取 binary log 状态

我们这里先获取 binary log 状态,供之后从服务器设置使用。

8.4 ?之前:

show master status;

8.4 之后:

show binary log status;

输出形式如下,我们需要记住其文件名和 Positon 值。

mysql> show binary log status;
+---------------+----------+--------------+------------------+-------------------+
| File          | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set |
+---------------+----------+--------------+------------------+-------------------+
| binlog.000002 |      158 |              |                  |                   |
+---------------+----------+--------------+------------------+-------------------+
1 row in set (0.00 sec)

根据 8.4 官方文档show master status 已完全弃用,改为 show binary log status。(具体开始时间未知)
8.0.22 声明将弃用的 show slave status 也已完全弃用。

从服务器详细步骤

提前设置

在从服务器的配置文件(my.cnf)中找到 [mysqld],修改以下参数:

[mysqld]

server-id = 2 # 设置服务器 ID,每个主服务器和从服务器都必须有唯一的 ID

重启从服务器,让以上配置生效。

设置复制主服务器

这里设置主服务器的地址、用户信息等配置,用于指明复制来源。

8.0.23 之前:

change master to master_host='master_ip',
master_user='repl', master_password='password',
master_log_file='binlog_file',
master_log_pos=log_file_position;

如果需要更改端口,比如端口号为 33060,则在其中添加 master_port=33060

8.0.23 及之后:

change replication source to source_host='source_ip',
source_user='repl', source_password='password',
source_log_file='binlog_file',
source_log_pos=log_file_position;

8.0 官方文档提到:In MySQL 8.0.23 and later, use CHANGE REPLICATION SOURCE TO in place of the deprecated CHANGE MASTER TO statement.

启动复制服务

8.0.22 之前:

start slave

类似的,你应该能推测出来停止复制应该是 stop slave

8.0.22 之后:

start replica

查看复制状态

8.0.22 之前:

show slave status \G;

8.0.22 之后:

show replica status \G;

根据 8.0 官方文档,8.22 之后用 show replica status 代替了 show slave status,后者仍可使用但有警告。而 show master status 没有替代。

开头部分如下:

mysql> show replica status\G
*************************** 1. row ***************************
            Replica_IO_State: Waiting for source to send event
                  Source_Host: xxx
                  Source_User: repl
                  Source_Port: 33060
                Connect_Retry: 1
              Source_Log_File: binlog.000002
          Read_Source_Log_Pos: 927
              Relay_Log_File: slave-relay-bin.000002
                Relay_Log_Pos: 158
        Relay_Source_Log_File: binlog.000002
          Replica_IO_Running: Yes
          Replica_SQL_Running: Yes

注意这里的最后两行,确保 Replica_IO_RunningReplica_SQL_Running 都为 Yes,这时复制就开始了。