技术咨询、项目合作、广告投放、简历咨询、技术文档下载 点击这里 联系博主

# 使用 Docker 进行 MySQL 主从复制

# 为什么要主从复制

  • 做数据的热备

  • 如果主数据库宕机,可以快速将业务系统切换到从数据库上,可避免数据丢失。

  • 业务量越来越大,I/O 访问频率过高,单机无法满足,此时做多库的存储,降低磁盘 I/O 访问的频率,提高单个机器的 I/O 性能。如果对数据库的读和写都在同一个数据库服务器中操作,业务系统性能会降低。

  • 在业务复杂的系统中,有这么一个情景,有一句 sql 语句需要锁表,导致暂时不能使用读的服务,那么就很影响运行中的业务,使用主从复制,让主库负责写,从库负责读,这样,即使主库出现了锁表的情景,通过读从库也可以保证业务的正常运作。通过做主从复制(读写分离)来减轻主数据库的负载。

# 原理

  • 步骤一:主库db的更新事件(update、insert、delete)被写到binlog
  • 步骤二:从库发起连接,连接到主库
  • 步骤三:此时主库创建一个binlog dump thread,把binlog的内容发送到从库
  • 步骤四:从库启动之后,创建一个I/O线程,读取主库传过来的binlog内容并写入到relay log
  • 步骤五:还会创建一个SQL线程,从relay log里面读取内容,从Exec_Master_Log_Pos位置开始执行读取到的更新事件,将更新内容写入到slave的db

注:上面的解释是解释每一步做了什么,整个mysql主从复制是异步的,不是按照上面的步骤执行的。

同步操作通过 3 个线程实现,其基本步骤如下:

主服务器将数据的更新记录到二进制日志中(记录被称作二进制日志事件)-- 主库线程;
从库将主库的二进制日志复制到本地的中继日志(relay log)-- 从库 I/O 线程;
从库读取中继日志中的事件,将其重放到数据中 -- 从库 SQL 线程。

# 主实例搭建

  • 运行 mysql 主实例:
docker run -p 3307:3306 --name mysql-master \
-v /your_absolute_project_path/mysql-master/log:/var/log/mysql \
-v /your_absolute_project_path/mysql-master/data:/var/lib/mysql \
-v /your_absolute_project_path/mysql-master/conf:/etc/mysql \
-e MYSQL_ROOT_PASSWORD=root  \
-dit mysql:5.7

  • 在 mysql 的配置文件夹/your_absolute_project_path/mysql-master/conf中创建一个配置文件my.cnf
touch my.cnf

  • 修改配置文件 my.cnf,配置信息如下:
[mysqld]
## 设置server_id,同一局域网中需要唯一
server_id=101
## 指定不需要同步的数据库名称
binlog-ignore-db=mysql
## 开启二进制日志功能
log-bin=mall-mysql-bin
## 设置二进制日志使用内存大小(事务)
binlog_cache_size=1M
## 设置使用的二进制日志格式(mixed,statement,row)
binlog_format=mixed
## 二进制日志过期清理时间。默认值为0,表示不自动清理。
expire_logs_days=7
## 跳过主从复制中遇到的所有错误或指定类型的错误,避免slave端复制中断。
## 如:1062错误是指一些主键重复,1032错误是因为主从数据库数据不一致
slave_skip_errors=1062

  • 修改完配置后重启实例:
docker restart mysql-master

  • 进入mysql-master容器中:
docker exec -it mysql-master /bin/bash

  • 在容器中使用 mysql 的登录命令连接到客户端:
mysql -uroot -proot

  • 创建数据同步用户:
CREATE USER 'slave-one'@'%' IDENTIFIED BY '123456';
GRANT REPLICATION SLAVE, REPLICATION CLIENT ON *.* TO 'slave-one'@'%';
flush privileges;

# 从实例搭建

  • 运行 mysql 从实例:
docker run -p 3308:3306 --name mysql-slave \
-v /your_absolute_project_path/mysql-slave/log:/var/log/mysql \
-v /your_absolute_project_path/mysql-slave/data:/var/lib/mysql \
-v /your_absolute_project_path/mysql-slave/conf:/etc/mysql \
-e MYSQL_ROOT_PASSWORD=root  \
-dit mysql:5.7

  • 在 mysql 的配置文件夹/your_absolute_project_path/mysql-slave/conf中创建一个配置文件my.cnf
touch my.cnf

  • 修改配置文件 my.cnf:
[mysqld]
## 设置server_id,同一局域网中需要唯一
server_id=102
## 指定不需要同步的数据库名称
binlog-ignore-db=mysql
## 开启二进制日志功能,以备Slave作为其它数据库实例的Master时使用
log-bin=mall-mysql-slave1-bin
## 设置二进制日志使用内存大小(事务)
binlog_cache_size=1M
## 设置使用的二进制日志格式(mixed,statement,row)
binlog_format=mixed
## 二进制日志过期清理时间。默认值为0,表示不自动清理。
expire_logs_days=7
## 跳过主从复制中遇到的所有错误或指定类型的错误,避免slave端复制中断。
## 如:1062错误是指一些主键重复,1032错误是因为主从数据库数据不一致
slave_skip_errors=1062
## relay_log配置中继日志
relay_log=mall-mysql-relay-bin
## log_slave_updates表示slave将复制事件写进自己的二进制日志
log_slave_updates=1
## slave设置为只读(具有super权限的用户除外)
read_only=1

  • 修改完配置后重启实例:
docker restart mysql-slave

# 将主从数据库进行连接

  • 连接到主数据库的 mysql 客户端,查看主数据库状态:
show master status;

  • 主数据库状态显示如下:
mysql> show master status;
+-----------------------+----------+--------------+------------------+-------------------+
| File                  | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set |
+-----------------------+----------+--------------+------------------+-------------------+
| mall-mysql-bin.000001 |      777 |              |                  |                   |
+-----------------------+----------+--------------+------------------+-------------------+
1 row in set (0.00 sec)
  • 进入mysql-slave容器中:
docker exec -it mysql-slave /bin/bash

  • 在容器中使用 mysql 的登录命令连接到客户端:
mysql -uroot -proot

  • 在从数据库中配置主从复制:
# 记得切换自己的ip以及端口和log_file
change master to master_host='10.64.67.71', master_user='slave-one', master_password='123456', master_port=3307, master_log_file='mall-mysql-bin.000001', master_log_pos=777, master_connect_retry=30;

  • 主从复制命令参数说明:

    • master_host:主数据库的 IP 地址;
    • master_port:主数据库的运行端口;
    • master_user:在主数据库创建的用于同步数据的用户账号;
    • master_password:在主数据库创建的用于同步数据的用户密码;
    • master_log_file:指定从数据库要复制数据的日志文件,通过查看主数据的状态,获取 File 参数;
    • master_log_pos:指定从数据库从哪个位置开始复制数据,通过查看主数据的状态,获取 Position 参数;
    • master_connect_retry:连接失败重试的时间间隔,单位为秒。
  • 查看主从同步状态:

show slave status \G;

  • 从数据库状态显示如下:
mysql> show slave status \G;
*************************** 1. row ***************************
               Slave_IO_State:
                  Master_Host: 10.64.67.71
                  Master_User: slave
                  Master_Port: 3307
                Connect_Retry: 30
              Master_Log_File: mall-mysql-bin.000001
          Read_Master_Log_Pos: 777
               Relay_Log_File: b72cade3208a-relay-bin.000001
                Relay_Log_Pos: 4
        Relay_Master_Log_File: mall-mysql-bin.000001
             Slave_IO_Running: No # 表示还没有开启同步
            Slave_SQL_Running: No # 表示还没有开启同步
              Replicate_Do_DB:
          Replicate_Ignore_DB:
           Replicate_Do_Table:
       Replicate_Ignore_Table:
      Replicate_Wild_Do_Table:
  Replicate_Wild_Ignore_Table:
                   Last_Errno: 0
                   Last_Error:
                 Skip_Counter: 0
          Exec_Master_Log_Pos: 777
              Relay_Log_Space: 154
              Until_Condition: None
               Until_Log_File:
                Until_Log_Pos: 0
           Master_SSL_Allowed: No
           Master_SSL_CA_File:
           Master_SSL_CA_Path:
              Master_SSL_Cert:
            Master_SSL_Cipher:
               Master_SSL_Key:
        Seconds_Behind_Master: NULL
Master_SSL_Verify_Server_Cert: No
                Last_IO_Errno: 0
                Last_IO_Error:
               Last_SQL_Errno: 0
               Last_SQL_Error:
  Replicate_Ignore_Server_Ids:
             Master_Server_Id: 0
                  Master_UUID:
             Master_Info_File: /var/lib/mysql/master.info
                    SQL_Delay: 0
          SQL_Remaining_Delay: NULL
      Slave_SQL_Running_State:
           Master_Retry_Count: 86400
                  Master_Bind:
      Last_IO_Error_Timestamp:
     Last_SQL_Error_Timestamp:
               Master_SSL_Crl:
           Master_SSL_Crlpath:
           Retrieved_Gtid_Set:
            Executed_Gtid_Set:
                Auto_Position: 0
         Replicate_Rewrite_DB:
                 Channel_Name:
           Master_TLS_Version:
1 row in set (0.00 sec)
  • 开启主从同步:
start slave;
# 关闭主从使用stop slave;
  • 查看从数据库状态发现已经同步:
mysql> show slave status \G;
*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: 10.64.67.71
                  Master_User: slave-one
                  Master_Port: 3307
                Connect_Retry: 30
              Master_Log_File: mall-mysql-bin.000001
          Read_Master_Log_Pos: 936
               Relay_Log_File: b72cade3208a-relay-bin.000002
                Relay_Log_Pos: 484
        Relay_Master_Log_File: mall-mysql-bin.000001
             Slave_IO_Running: Yes # 表示已经开启同步了
            Slave_SQL_Running: Yes
              Replicate_Do_DB:
          Replicate_Ignore_DB:
           Replicate_Do_Table:
       Replicate_Ignore_Table:
      Replicate_Wild_Do_Table:
  Replicate_Wild_Ignore_Table:
                   Last_Errno: 0
                   Last_Error:
                 Skip_Counter: 0
          Exec_Master_Log_Pos: 936
              Relay_Log_Space: 698
              Until_Condition: None
               Until_Log_File:
                Until_Log_Pos: 0
           Master_SSL_Allowed: No
           Master_SSL_CA_File:
           Master_SSL_CA_Path:
              Master_SSL_Cert:
            Master_SSL_Cipher:
               Master_SSL_Key:
        Seconds_Behind_Master: 0
Master_SSL_Verify_Server_Cert: No
                Last_IO_Errno: 0
                Last_IO_Error:
               Last_SQL_Errno: 0
               Last_SQL_Error:
  Replicate_Ignore_Server_Ids:
             Master_Server_Id: 101
                  Master_UUID: 9d05ada9-03e7-11ec-b838-0242ac110003
             Master_Info_File: /var/lib/mysql/master.info
                    SQL_Delay: 0
          SQL_Remaining_Delay: NULL
      Slave_SQL_Running_State: Slave has read all relay log; waiting for more updates
           Master_Retry_Count: 86400
                  Master_Bind:
      Last_IO_Error_Timestamp:
     Last_SQL_Error_Timestamp:
               Master_SSL_Crl:
           Master_SSL_Crlpath:
           Retrieved_Gtid_Set:
            Executed_Gtid_Set:
                Auto_Position: 0
         Replicate_Rewrite_DB:
                 Channel_Name:
           Master_TLS_Version:
1 row in set (0.00 sec)

# 主从复制测试

主从复制的测试方法有很多,可以在主实例中创建一个数据库,看看从实例中是否有该数据库,如果有,表示主从复制已经搭建成功。

  • 在主实例中创建一个数据库mall

  • 在从实例中查看数据库,发现也有一个mall数据库,可以判断主从复制已经搭建成功。

  • 在主数据库中创建一个表
mysql> use mall;
Database changed
mysql> CREATE TABLE IF NOT EXISTS `runoob_tbl`(
    ->    `runoob_id` INT UNSIGNED AUTO_INCREMENT,
    ->    `runoob_title` VARCHAR(100) NOT NULL,
    ->    `runoob_author` VARCHAR(40) NOT NULL,
    ->    `submission_date` DATE,
    ->    PRIMARY KEY ( `runoob_id` )
    -> )ENGINE=InnoDB DEFAULT CHARSET=utf8;
Query OK, 0 rows affected (0.04 sec)
  • 在从数据库中查看
mysql> show tables;
+----------------+
| Tables_in_mall |
+----------------+
| runoob_tbl     |
+----------------+
1 row in set (0.00 sec)

# 参考

【未经作者允许禁止转载】 Last Updated: 2/4/2024, 6:06:40 AM