【Mysql主从复制】1主多从

发布时间 2023-09-27 11:03:29作者: PythonNew_Mr.Wang

这里使用docker进行演示两台mysql主从搭建



1:使用 Docker 启动 俩个Mysql容器,配置挂载数据与配置文件

传送门:https://www.cnblogs.com/wanghong1994/p/17731143.html
创建完后应该就有俩个Mysql(或者你有两个服务器,启动了mysql并且配置完成):
    [root@VM-12-9-centos /]# docker ps
    CONTAINER ID   IMAGE          COMMAND                  CREATED             STATUS             PORTS                                                  NAMES
    e038c31025cc   99afc808f15b   "docker-entrypoint.s…"   3 seconds ago       Up 2 seconds       33060/tcp, 0.0.0.0:3307->3306/tcp, :::3307->3306/tcp   mysql_02
    7130169975c3   99afc808f15b   "docker-entrypoint.s…"   About an hour ago   Up About an hour   0.0.0.0:3306->3306/tcp, :::3306->3306/tcp, 33060/tcp   mysql_01



2:备份主已经拥有的历史数据(如果从0开始搭建跳过此步骤)

2-1:确保开启二进制日志后,进行clone数据同步:		
    clone instance from 'mysql://username:password@source_host:3306/dbname';
    # username:源服务器上具有适当权限的MySQL用户的用户名。
    # password:源服务器上具有适当权限的MySQL用户的密码。
    # source_hostname:源服务器的主机名或IP地址。
    # exampledb:要复制的源数据库的名称。
    
2-2:直接导入源数据sql备份文件



3:主从服务器 配置文件

3-1: 配置主服务器的my.cnf
server-id = 1
read_only = 0

3-2: 配置从服务器的my.cnf
server-id = 2
read_only = 1

提示:如果登录mysql后,并没有生效,可以直接在mysql中进行修改



4:主服务器配置

# 检查:开启binlogs 默认下是开启的;可以使用show master status;进行查看状态

4-1: 创建用户(your_host可以是'%','localhost','IP地址') , 刷新信息
create user ''@'your_host' identified by 'your_password';

4-2: 进行授权从权限
grant replication slave on *.* to '用户名'@'your_host';

4-3:刷新
flush privileges; 

4-4:获取二进制日志文件的的位置
show master status;
+---------------+----------+--------------+------------------+-------------------+
| File          | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set |
+---------------+----------+--------------+------------------+-------------------+
| binlog.000004 |      858 |              |                  |                   |
+---------------+----------+--------------+------------------+-------------------+



5:从服务器配置

# 检查:
# 开启binlogs 默认下是开启的;可以使用show master status;进行查看状态
# show variables like 'server_id'; 是否等于2或者其他
# show variables like 'read_only'; 是否够等于1
# 登录后手动修改ID:set global server_id = 2;
# 登录后手动修改ID:set global read_only = 1;

5-1: 登录服务器后输入以下参数
change master to master_host = 'xx.xx.xx.xx',
master_user = '',
master_password = '',
master_log_file = '上面的File',
master_log_pos = 上面的Position;

5-2:开始
start slave;

5-3: 查看复制状态,俩都是YES才是成功
show slave status\G
Slave_IO_Running: Yes
Slave_SQL_Running: Yes




报错以及处理:



# 报错提示:
  ERROR 3021 (HY000): This operation cannot be performed with a running replica io thread; run STOP REPLICA IO_THREAD FOR CHANNEL '' first.
# 处理: 
  STOP REPLICA IO_THREAD FOR CHANNEL '';  # 先停止复制IO线程



# 报错提示:
ERROR 1872 (HY000): Replica failed to initialize applier metadata structure from the repository
# 处理:
STOP SLAVE;
RESET SLAVE;
SET GLOBAL server_id = 2;
# 接着配置从服务器参数