一.背景
有的项目初期阶段数据库只是单台节点,中期或后期阶段,需要具备数据冗余或者读写分离功能,这个时候需要对单数据库进行扩容,实现高可用
二.实现方案
方案1
搭建一套新的集群,对现有单节点数据库执行lock table write进行写锁,随后导出数据再导入至新的集群中,并修改应用程序配置指明新的数据库;这个过程较为繁琐,同时影响业务,工作人员在规定的时间完成会有很大压力
方案2
新部署一台数据库节点,在线扩容为集群形式,这里以主从为例
三.实现案例
1. 基础环境
IP | 角色 |
---|---|
39.107.13.9 | 现有节点,集群角色为主 |
39.105.11.14 | 新增节点,集群角色为备 |
2. slave节点关联master
mysql> change master to master_host='39.107.13.9',master_port=38383,master_user='wtc',master_password='wtc.com',master_log_file='mysql-bin.000001',master_log_pos=177;
Query OK, 0 rows affected, 2 warnings (0.03 sec)
3. 检测slave状态
mysql> show slave status\G;
*************************** 1. row ***************************
Slave_IO_State: Waiting for master to send event
Master_Host: 39.107.13.12
Master_User: wtc
Master_Port: 38383
Connect_Retry: 60
Master_Log_File: mysql-bin.000003
Read_Master_Log_Pos: 3931784
Relay_Log_File: relay-log.000004
Relay_Log_Pos: 3500131
Relay_Master_Log_File: mysql-bin.000003
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: 3499918
Relay_Log_Space: 3933277
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: 1
Master_UUID: 122574bd-7926-11ec-85dc-00163e366a62
Master_Info_File: /opt/app/mysql/data/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)
3.确认数据
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| sys |
| wtc |
+--------------------+
5 rows in set (0.00 sec)
mysql> use wtc
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed
mysql> select count(1) from wtc_table;
+----------+
| count(1) |
+----------+
| 100000 |
+----------+
有几点需要注意
1.新增节点同步需要指明现有集群的最初的二进制日志、posid,这样所有的数据才会同步
2.历史二进制文件得存在,或者异地备份,可通过show binary logs确认是否加载,异地迁回后需要在mysql-bin.index新增历史二进制文件路径并重启服务
四. 问题深入
1. 若新增节点想构成双主集群,应该如何做?
1.新增节点需开启binlog、relaylog,同时关闭read-only2.在数据库上游新增代理,如MySQLRouter服务,将行请求转发至新增节点
3.老节点开启relaylog、关闭read-only,新节点创建授权用户进行复制,同时指明老节点最新的postid(待验证)