本文mysql采用8.0.35版本,master-slave架构
正常切换
1)master执行
先检查slave同步状态,同时为yes时才可进行切换。在开始之前对主库进行锁表:
#主:flush tables with read lock
show processlist;
显示 master(source) has sent all binlog to slave;waiting for binlog to be updated //主节点已经发送所有binlog日志文件到从节点,等待binlog日志文件更新,说明无新增写入。
2)slave执行
show processlist;
显示Slave has read all relay log; waiting for the slave I/O thread to update it //从节点已经读取所有从主节点接收并执行的二进制日志,等待从节点的i/o 更新它
show slave status\G; //检查io及sql线程状态,确保都是yes
停止slave io线程,在slave执行
stop slave io_thread;
show processlist;
确保显示为: has read all relay log. 保证数据没有新写入
---------------------------------至此可以进行切换-------------------------------
3)提升slave为master
从节点执行:
stop slave;
reset master;
reset slave;
//查看从节点是否是只读模式 show variables like 'read_only'; 门户设置的OFF,不需要调整
show master status\G
4) 将原来的master变为slave
在新的master上创建同步用户
新的master执行:
CREATE USER 'repl_user'@'%' IDENTIFIED BY 'Repl_user_xxx';
//创建授权同步用户repl_user
GRANT REPLICATION SLAVE ON *.* TO 'repl_user'@'%'; //授予权限(root用户操作或者有grant权限的用户)
FLUSH PRIVILEGES; //刷新权限
旧master执行:
reset master;
change master to
MASTER_HOST='10.xxx.xx.xx',
MASTER_PORT=3306,
MASTER_USER='repl_user',
MASTER_PASSWORD='Repl_user_xxx',
MASTER_LOG_FILE='bin.00000x',
MASTER_LOG_POS=xxx;
//启动slave
start slave;
show slave status\G
//释放锁
unlock tables;
- 同时nacos配置中心mysql.yml 也需要调整主从节点ip
- 重启服务
- 验证业务
异常切换
主机故障或者宕机
1)在slave节点执行:
stop slave;
reset master;
查看节点读写模式,关闭只读模式
show variables like 'read_only';
SET GLOBAL read_only = ON; //开启只读模式,临时生效
SET GLOBAL read_only = OFF; //关闭只读模式,临时生效
永久设置:my.cnf
#read-only=1 //设置 MySQL 服务器为只读模式。关闭注释就好
查看show slave status \G;
查看show master status \G;
业务侧nacos配置文件mysql.yml将从库IP地址改为主库IP地址。