17-数据库平滑扩容

发布时间 2023-12-10 21:14:42作者: tree6x7

1. 扩容问题

B+树,一般就三层,上边两层是索引,最后一层是数据记录。

扇区:4k,一页:16k

假设一条数据记录: 1k => 一页可以放16条记录

上面两层,每一个 item 的结构是:[索引 6B, 主键 8B]

16k*1024 = 16384(B)

16384 / (6+8) = 1170 => 一层可存放 1170 个 item

1170*1170 = 1369234 => 两层可存放的记录

1369234*16 = 21907748 => 三层 · 2kw 记录


在项目初期,我们部署了三个数据库 A、B、C,此时数据库的规模可以满足我们的业务需求。为了将数据做到平均分配,我们在服务层使用 uid%3 进行取模分片,从而将数据平均分配到三个数据库中。

后期随着用户量的增加,用户产生的数据信息被源源不断的添加到数据库中,最终达到数据库的最佳存储容量。如果此时继续向数据库中新增数据,会导致数据库的 CRUD 等基本操作变慢,进而影响整个服务的响应速度。

这时,我们需要增加新的节点,对数据库进行水平扩容,那么加入新的数据库 D 后,数据库的规模由原来的 3 个变为 4 个。

此时由于分片规则发生了变化(uid%3 变为 uid%4),导致大部分的数据,无法命中原有的数据,需要重新进行分配,要做大量的数据迁移处理。

新增一个节点, 大概会有 90% 的数据需要迁移, 这样会面临大量的数据压力,并且对服务造成极大的不稳定性。

2. 扩容方案剖析

2.1 停机方案

  1. 【发布公告】为了进行数据的重新拆分,在停止服务之前,我们需要提前通知用户,比如:我们的服务会在yyyy-MM-dd进行升级,给您带来的不便敬请谅解。
  2. 【停止服务】关闭 Service
  3. 【离线数据迁移】将旧库中的数据按照 Service 层的算法,将数据拆分,重新分配数据。
  4. 【数据校验】开发定制一个程序对旧库和新库中的数据进行校验、比对。
  5. 【更改配置】修改 Service 层的配置算法,也就是将原来的 uid%3 变为 uid%4。
  6. 【恢复服务】重启 Service 服务。
  7. 【回滚预案】针对上述的每个步骤都要有数据回滚预案,一旦某个环节(如:数据迁移、恢复服务等)执行失败,立刻进行回滚,重新再来。

停止服务之后, 能够保证迁移工作的正常进行, 但是服务停止,伤害用户体验, 并造成了时间压力, 必须在指定的时间内完成迁移。

2.2 停写方案

  1. 【支持读写分离】数据库支持读写分离,在扩容之前,每个数据库都提供了读写功能,数据重新分配的过程中,将每个数据库设置为只读状态,关闭写的功能。
  2. 【升级公告】为了进行数据的重新拆分,在停写之前,我们需要提前通知用户,如:我们的服务会在 yyyy-MM-dd 进行升级,给您带来的不便敬请谅解。
  3. 【中断写操作】在 Service 层对所有的写请求进行拦截,统一返回提示信息,如:服务正在升级中,只对外提供读服务。
  4. 【数据同步处理】将旧库中的数据按照 Service 层的算法,将数据重新分配、迁移(复制数据)。
  5. 【数据校验】开发定制一个程序对旧库中的数据进行备份,使用备份的数据和重新分配后的数据进行校验、比对。
  6. 【更改配置】通过配置中心,修改 Service 层的配置算法,也就是将原来的 uid%3 变为 uid%4,这个过程不需要重启服务。
  7. 【恢复写操作】设置数据库恢复读写功能,去除 Service 层的拦截提示。
  8. 【数据清理】使用 delete 语句对冗余数据进行删除。
  9. 【回滚预案】针对上述的每个步骤都要有数据回滚预案,一旦某个环节(如:数据迁移等)执行失败,立刻进行回滚,重新再来。

缺点:在数据的复制过程需要消耗大量的时间,停写时间太长,数据需要先复制,再清理冗余数据。

2.3 日志方案

核心是通过日志进行数据库的同步迁移, 主要操作步骤如下:

(1)数据迁移之前, 业务应用访问旧的数据库节点

(2)日志记录

在升级之前, 记录“对旧数据库上的数据修改”的日志(这里修改包括增、删、改),这个日志不需要记录详细的数据信息,主要记录:

  1. 修改的库
  2. 修改的表
  3. 修改的唯一主键
  4. 修改操作类型

日志记录不用关注新增了哪些信息,修改的数据格式,只需要记录以上数据信息,这样日志格式是固定的,这样能保证方案的通用性。

服务升级日志记录功能风险较小:写和修改接口是少数,改动点少;升级只是增加了一些日志,采用异步方式实现, 对业务功能没有太多影响。

(3)数据迁移

研发定制数据迁移工具, 作用是把旧库中的数据迁移至新库中。

  • 整个过程仍然采用旧库进行对外服务。
  • 数据同步工具实现复杂度不高。只对旧库进行读取操作, 如果同步出现问题, 都可以对新库进行回滚操作。可以限速或分批迁移执行, 不会有时间压力。
  • 数据迁移完成之后,并不能切换至新库提供服务。因为旧库依然对线上提供服务,库中的数据随时会发生变化,但这些变化的数据并没有同步到新库中,旧库和新库数据不一致,所以不能直接进行切换,需要将数据同步完整。

(4)日志增量迁移

研发一个日志迁移工具,把上面迁移数据过程中的差异数据追平,处理步骤如下:

  1. 读取 log 日志,获取具体是哪个库、表和主键发生了变化修改;
  2. 把旧库中的主键记录读取出来;
  3. 根据主键 ID,把新库中的记录替换掉。

这样可以最大程度的保障数据的一致性。风险分析:

  • 整个过程,仍然是旧库对线上提供服务;
  • 日志迁移工具实现的复杂度较低;
  • 任何时间发现问题,可以重新再来,有充分的容错空间;
  • 可以限速重放处理日志,处理过程不会因为对线上影响造成时间压力。

但是,日志增量同步完成之后,还不能切换到新的数据库。因为日志增量同步过程中,旧库中可能有数据发生变化,导致数据不一致,所以需要进一步读取日志,追平数据记录。日志增量同步过程随时可能会产生新的数据,新库与旧库的数据追平也会是一个无限逼近的过程。

(5)数据校验

准备好数据校验工具,将旧库和新库中的数据进行比对,直到数据完全一致。

2.4 双写方案

双写方案可通过 Canal 或 MQ 做实现。

  1. 【增加新库】按照现有节点,增加对应的数量。
  2. 【数据迁移】避免增量影响,先断开主从,再导入(耗时较长),同步完成并做校验。
  3. 【增量同步】开启 Canal 同步服务,监听从节点数据库,再开启主从同步,从节点收到数据后会通过 Canal 服务,传递至新的 DB 节点。
  4. 【切换新库】通过 Nginx,切换访问流量至新的服务。
  5. 【修复切换异常数据】在切换过程中, 如果出现 Canal 未同步,但已切换至新库的请求(比如下单,修改了资金,但还未同步),可以通过定制程序,读取检测异常日志,做自动修复或人工处理。针对此种情况, 最好是在凌晨用户量小的时候,或专门停止外网访问,进行切换,减少异常数据的产生。
  6. 【数据校验】为保障数据的完全一致, 有必要对数据的数量完整性做校验。

2.5 平滑2N方案

(1)线上数据库,为了保障其高可用,一般每台主库会配置一台从库,主库负责读写,从库负责读取。下图所示,A/B 是主库,A0/B0 是从库。

(2)当需要扩容的时候,我们把 A0 和 B0 升级为新的主库节点,如此由 2 个分库变为 4 个分库。同时在上层的分片配置,做好映射,规则如下:

  • 【偶】把 uid%4=0 和 uid%4=2 的数据分别分配到 A 和 A0 主库中
  • 【奇】把 uid%4=1 和 uid%4=3 的数据分别分配到 B 和 B0 主库中

(3)因为 A 和 A0 库的数据相同,B 和 B0 数据相同,此时无需做数据迁移。只需调整变更一下分片配置即可,通过配置中心更新,不需要重启。

由于之前 uid%2 的数据是分配在 2 个库里面,扩容之后需要分布到 4 个库中,但由于旧数据仍存在(uid%4=0 的节点,还有一半 uid%4=2 的数据),所以需要对冗余数据做一次清理(这个清理并不会影响线上数据的一致性,可以随时随地进行)。

(4)处理完成之后,为保证数据的高可用,以及将来下一步的扩容需求。可以为现有的主库再次分配一个从库。

平滑2N和之前的方案有个明显区别就是:先存冗余数据,就不需要数据迁移/同步了。后续只要删除多余的的数据。

3. 平滑2N实践

3.1 应用服务器级的动态扩容

a. MariaDB 服务安装

(0)如果之前已经安装, 需要先删除(之前没有安装,可忽略此步骤)

# a. 停止Mariadb服务
[root@localhost yum.repos.d]# ps -ef | grep mysql
root       1954      1  0 Oct04 ?        00:05:43 /usr/sbin/mysqld --wsrep-new-cluster --user=root
root      89521  81403  0 07:40 pts/0    00:00:00 grep --color=auto mysql
[root@localhost yum.repos.d]# kill 1954

# b. 卸载Mariadb服务
yum -y remove Maria*

# c. 删除数据与配置
rm -rf /var/lib/mysql/*
rm -rf /etc/my.cnf.d/
rm -rf /etc/my.cnf

(1)配置 YUM 源

[root@linux30 ~]# vi /etc/yum.repos.d/mariadb-10.2.repo

[mariadb]
name = MariaDB
baseurl = https://mirrors.ustc.edu.cn/mariadb/yum/10.2/centos7-amd64
gpgkey=https://yum.mariadb.org/RPM-GPG-KEY-MariaDB
gpgcheck=1

(2)执行安装

[root@linux30 ~]# yum -y install mariadb mariadb-server MariaDB-client  MariaDB-common

(3)启动 MariaDB

[root@linux30 ~]# systemctl start mariadb

# --- 执行安全配置向导命令,可根据安全配置向导提高数据库的安全性 ---
[root@linux30 ~]# mysql_secure_installation

NOTE: RUNNING ALL PARTS OF THIS SCRIPT IS RECOMMENDED FOR ALL MariaDB
      SERVERS IN PRODUCTION USE!  PLEASE READ EACH STEP CAREFULLY!

In order to log into MariaDB to secure it, we'll need the current
password for the root user.  If you've just installed MariaDB, and
you haven't set the root password yet, the password will be blank,
so you should just press enter here.
# 首次安装,直接跳过
Enter current password for root (enter for none):
ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)
Enter current password for root (enter for none):
ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)
Enter current password for root (enter for none):
OK, successfully used password, moving on...

Setting the root password ensures that nobody can log into the MariaDB
root user without the proper authorisation.
# 设置root用户密码
Set root password? [Y/n] y
New password:
Re-enter new password:
Password updated successfully!
Reloading privilege tables..
 ... Success!


By default, a MariaDB installation has an anonymous user, allowing anyone
to log into MariaDB without having to have a user account created for
them.  This is intended only for testing, and to make the installation
go a bit smoother.  You should remove them before moving into a
production environment.
# 删除匿名用户
Remove anonymous users? [Y/n] y
 ... Success!

Normally, root should only be allowed to connect from 'localhost'.  This
ensures that someone cannot guess at the root password from the network.
# 允许root用户远程登录
Disallow root login remotely? [Y/n] n
 ... skipping.

By default, MariaDB comes with a database named 'test' that anyone can
access.  This is also intended only for testing, and should be removed
before moving into a production environment.
# 删除test数据库
Remove test database and access to it? [Y/n] y
 - Dropping test database...
 ... Success!
 - Removing privileges on test database...
 ... Success!

Reloading the privilege tables will ensure that all changes made so far
will take effect immediately.
# 刷新权限
Reload privilege tables now? [Y/n] y
 ... Success!

Cleaning up...

All done!  If you've completed all of the above steps, your MariaDB
installation should now be secure.

Thanks for using MariaDB!

(4)将连接用户root开启远程连接权限

[root@linux30 ~]# mysql -uroot -p123456
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 17
Server version: 10.2.41-MariaDB MariaDB Server

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
# 切换到mysql数据库
MariaDB [(none)]> use mysql;
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
# 删除所有用户
MariaDB [mysql]> delete from user;
Query OK, 4 rows affected (0.00 sec)
# 配置root用户使用密码123456从任何主机都可以连接到mysql服务器
MariaDB [mysql]> GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY '123456' WITH GRANT OPTION;
Query OK, 0 rows affected (0.00 sec)
# 刷新权限
MariaDB [mysql]> FLUSH PRIVILEGES;
Query OK, 0 rows affected (0.00 sec)

MariaDB [mysql]>

b. MariaDB 双主同步

(1)在 linux30 的 /etc/my.cnf 中添加以下配置

[root@linux30 ~]# vi /etc/my.cnf

[mysqld]
server-id  = 1
log-bin=mysql-bin
relay-log=mysql-relay-bin
## 忽略mysql、information_schema库下对表的操作
replicate-wild-ignore-table=mysql.%
replicate-wild-ignore-table=information_schema.%
## 默认的情况下mysql是关闭的
log-slave-updates=on
## 复制过程中,有任何错误,直接跳过
slave-skip-errors=all
auto-increment-offset=1
auto-increment-increment=2
## binlog的格式:STATEMENT ROW MIXED
binlog_format=mixed
## 自动过期清理binlog,默认0天,即不自动清理
expire_logs_days=10

注意,自增 ID 的生成是基于当前数据库中最大的 ID 值。

linux30 自增为奇数位:

  • auto-increment-offset=1 主键自增基数,从 1 开始。
  • auto-increment-increment=2 主键自增偏移量,每次为 2。

(2)在 linux31 的 /etc/my.cnf 中添加以下配置

[root@linux31 ~]# vi /etc/my.cnf

[mysqld]
server-id = 2
log-bin=mysql-bin
relay-log = mysql-relay-bin
replicate-wild-ignore-table=mysql.%
replicate-wild-ignore-table=information_schema.%
log-slave-updates=on
slave-skip-errors=all
auto-increment-offset=2
auto-increment-increment=2
binlog_format=mixed
expire_logs_days=10

linux31 自增为偶数位:

  • auto-increment-offset=2 主键自增基数,从 2 开始;
  • auto-increment-increment=2 主键自增偏移量,每次为 2;

以上配置修改完成后,重启数据库。

(3)同步授权配置

在 linux30 创建用于主从同步的用户:

[root@linux30 ~]# mysql -uroot -p123456
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 9
Server version: 10.2.41-MariaDB-log MariaDB Server

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

## 授权 replica 用户 replication slave, replication client 权限
MariaDB [(none)]> grant replication slave, replication client on *.* to 'replica'@'%' identified by 'replica';
Query OK, 0 rows affected (0.00 sec)

## 刷新权限
MariaDB [(none)]> flush privileges;
Query OK, 0 rows affected (0.01 sec)

## 查询日志文件与偏移量,开启同步时需使用
MariaDB [(none)]> show master status;
+------------------+----------+--------------+------------------+
| File             | Position | Binlog_Do_DB | Binlog_Ignore_DB |
+------------------+----------+--------------+------------------+
| mysql-bin.000001 |      663 |              |                  |
+------------------+----------+--------------+------------------+
1 row in set (0.00 sec)

同样, 在 linux31 创建用于主从同步的用户:

[root@linux31 ~]# mysql -uroot -p123456

## 授权
MariaDB [(none)]> grant replication slave, replication client on *.* to 'replica'@'%' identified by 'replica';
Query OK, 0 rows affected (0.00 sec)

## 刷新权限
MariaDB [(none)]> flush privileges;
Query OK, 0 rows affected (0.00 sec)

## 查询日志文件与偏移量
MariaDB [(none)]> show master status;
+------------------+----------+--------------+------------------+
| File             | Position | Binlog_Do_DB | Binlog_Ignore_DB |
+------------------+----------+--------------+------------------+
| mysql-bin.000001 |      663 |              |                  |
+------------------+----------+--------------+------------------+
1 row in set (0.00 sec)

(4)配置主从同步信息

在 linux30 执行:

MariaDB [(none)]> change master to master_host='192.168.10.31',master_user='replica', master_password='replica', master_port=3306, master_log_file='mysql-bin.000001', master_log_pos=663, master_connect_retry=30;
Query OK, 0 rows affected (0.01 sec)

在 linux31 执行:

MariaDB [(none)]> change master to master_host='192.168.10.30',master_user='replica', master_password='replica', master_port=3306, master_log_file='mysql-bin.000001', master_log_pos=663, master_connect_retry=30;
Query OK, 0 rows affected (0.01 sec)

(5)开启双主同步

在 linux30 和 linux31 中分别执行:

MariaDB [(none)]> start slave;
Query OK, 0 rows affected (0.00 sec)

在 linux30 查询同步信息:

MariaDB [(none)]> show slave status\G;
*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: 192.168.10.31
                  Master_User: replica
                  Master_Port: 3306
                Connect_Retry: 30
              Master_Log_File: mysql-bin.000001
          Read_Master_Log_Pos: 663
               Relay_Log_File: mysql-relay-bin.000002
                Relay_Log_Pos: 555
        Relay_Master_Log_File: mysql-bin.000001
             Slave_IO_Running: Yes
            Slave_SQL_Running: Yes

...

在 linux31 查询同步信息:

MariaDB [(none)]> show slave status\G;
*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: 192.168.10.30
                  Master_User: replica
                  Master_Port: 3306
                Connect_Retry: 30
              Master_Log_File: mysql-bin.000001
          Read_Master_Log_Pos: 663
               Relay_Log_File: mysql-relay-bin.000002
                Relay_Log_Pos: 555
        Relay_Master_Log_File: mysql-bin.000001
             Slave_IO_Running: Yes
            Slave_SQL_Running: Yes

...

Slave_IO_Running 和 Slave_SQL_Running 都是 Yes,说明双主同步配置成功。

c. KeepAlived 安装配置

(1)在 linux30 与 linux31 两台节点安装 Keepalived

[root@linux30 ~]# yum -y install keepalived

(2)关闭防火墙

[root@linux30 ~]# systemctl stop firewalld
[root@linux30 ~]# systemctl disable firewalld
Removed symlink /etc/systemd/system/multi-user.target.wants/firewalld.service.
Removed symlink /etc/systemd/system/dbus-org.fedoraproject.FirewallD1.service.
[root@linux30 ~]# systemctl status firewalld
firewalld.service - firewalld - dynamic firewall daemon
   Loaded: loaded (/usr/lib/systemd/system/firewalld.service; disabled; vendor preset: enabled)
   Active: inactive (dead)
     Docs: man:firewalld(1)
     ...

(3)设置主机名称

# linux30节点
[root@linux30 ~]# hostnamectl set-hostname linux30
# linux31节点
[root@linux31 ~]# hostnamectl set-hostname linux31

(4)linux30 节点配置

[root@linux30 ~]# vi /etc/keepalived/keepalived.conf

global_defs {
   router_id linux30                          # 机器标识,和主机名保持一致,运行keepalived服务器的一个标识
}
vrrp_instance VI_1 {                          # vrrp实例定义
    state BACKUP                              # LVS的状态模式,MASTER代表主,BACKUP代表备份节点
    interface ens33                           # 绑定对外访问的网卡,vrrp实例绑定的网卡
    virtual_router_id 1101                    # 虚拟路由标示,同一个vrrp实例采用唯一标示
    priority 100                              # 优先级,100代表最大优先级,数字越大优先级越高
    advert_int 1                              # Master与Backup节点同步检查的时间间隔,单位是秒
    authentication {                          # 设置验证信息
        auth_type PASS                        # 有PASS和AH两种
        auth_pass 6666                        # 验证密码,BACKUP密码须相同
    }
    virtual_ipaddress {                       # KeepAlived虚拟的IP地址
        192.168.10.150
    }
}
virtual_server 192.168.10.150 3306 {          # 配置虚拟服务器IP与访问端口
    delay_loop 6                              # 健康检查时间
    lb_algo rr                                # 负载均衡调度算法,rr代表轮询
    lb_kind DR                                # 负载均衡转发规则 DR/NAT
    persistence_timeout 0                     # 会话保持时间,这里要做测试,所以设为0,实际可根据Session有效时间配置
    protocol TCP                              # 转发协议类型,支持TCP和UDP
    real_server 192.168.10.30 3306 {          # 配置服务器节点VIP1    
        notify_down /opt/mariaDB/mariadb.sh   # 当服务挂掉时,会执行此脚本,结束KeepAlived进程
        weight 1                              # 设置权重,越大权重越高
        TCP_CHECK {                           # 状态监测设置
            connect_timeout 10                # 超时配置,单位秒
            retry 3                           # 重试次数
            delay_before_retry 3              # 重试间隔
            connect_port 3306                 # 连接端口,和上面保持一致
        }
    }
}

创建关闭脚本 mariadb.sh

[root@linux30 mariaDB]# vi /opt/mariaDB/mariadb.sh
## 添加脚本内容 ##
pkill keepalived
################
[root@linux30 mariaDB]# chmod a+x mariadb.sh

(5)linux31 节点配置

[root@linux31 ~]# vi /etc/keepalived/keepalived.conf

global_defs {
   router_id linux31                          # 机器标识,和主机名保持一致,运行keepalived服务器的一个标识
}
vrrp_instance VI_1 {                          # vrrp实例定义
    state BACKUP                              # LVS的状态模式,MASTER代表主,BACKUP代表备份节点
    interface ens33                           # 绑定对外访问的网卡,vrrp实例绑定的网卡
    virtual_router_id 1101                    # 虚拟路由标示,同一个vrrp实例采用唯一标示
    priority  98                              # 优先级,100代表最大优先级,数字越大优先级越高
    advert_int 1                              # Master与Backup节点同步检查的时间间隔,单位是秒
    authentication {                          # 设置验证信息
        auth_type PASS                        # 有PASS和AH两种
        auth_pass 6666                        # 验证密码,BACKUP密码须相同
    }
    virtual_ipaddress {                       # KeepAlived虚拟的IP地址
        192.168.10.150
    }
}
virtual_server 192.168.10.150 3306 {          # 配置虚拟服务器IP与访问端口
    delay_loop 6                              # 健康检查时间
    lb_algo rr                                # 负载均衡调度算法,rr代表轮询
    lb_kind DR                                # 负载均衡转发规则 DR/NAT
    persistence_timeout 0                     # 会话保持时间,这里要做测试,所以设为0,实际可根据Session有效时间配置
    protocol TCP                              # 转发协议类型,支持TCP和UDP
    real_server 192.168.10.31 3306 {          # 配置服务器节点VIP1    
        notify_down /opt/mariaDB/mariadb.sh   # 当服务挂掉时,会执行此脚本,结束KeepAlived进程
        weight 1                              # 设置权重,越大权重越高
        TCP_CHECK {                           # 状态监测设置
            connect_timeout 10                # 超时配置,单位秒
            retry 3                           # 重试次数
            delay_before_retry 3              # 重试间隔
            connect_port 3306                 # 连接端口,和上面保持一致
        }
    }
}

和 30 的差异项:

router_id linux31               # 机器标识,和主机名保持一致
priority 98                     # 优先级,100代表最大优先级,数字越大优先级越高
real_server 192.168.10.31 3306  # 配置服务器节点linux31

注意,同一个vrrp实例采用唯一标示,且两台节点都设为 BACKUP。

virtual_router_id 1101
state BACKUP

如果不想重启后, 争夺备用节点的 VIP, 可以设置此项(这个配置只能设置在 Backup 主机上,而且这个主机优先级要比另外一台高)。

nopreempt

(6)停止主节点 MariaDB 服务, 验证是否自动切换

[root@linux30 mariaDB]# systemctl start keepalived
[root@linux31 mariaDB]# systemctl start keepalived

[root@linux30 mariaDB]# systemctl stop mariadb

[root@linux30 mariaDB]# systemctl start mariadb

3.2 数据库的秒级平滑2N扩容

a. 新增数据库 VIP

在 linux30 / linux31节点,增加 VIP:

[root@linux31 ~]# vi /etc/keepalived/keepalived.conf

global_defs {
   router_id linux31                          # 机器标识,和主机名保持一致,运行keepalived服务器的一个标识
}
vrrp_instance VI_1 {                          # vrrp实例定义
    state BACKUP                              # LVS的状态模式,MASTER代表主,BACKUP代表备份节点
    interface ens33                           # 绑定对外访问的网卡,vrrp实例绑定的网卡
    virtual_router_id 1234                    # 虚拟路由标示,同一个vrrp实例采用唯一标示
    priority  100                             # 优先级,100代表最大优先级,数字越大优先级越高
    advert_int 1                              # Master与Backup节点同步检查的时间间隔,单位是秒
    authentication {                          # 设置验证信息
        auth_type PASS                        # 有PASS和AH两种
        auth_pass 6666                        # 验证密码,BACKUP密码须相同
    }
    virtual_ipaddress {                       # KeepAlived虚拟的IP地址
        192.168.10.151
    }
}
virtual_server 192.168.10.150 3306 {          # 配置虚拟服务器IP与访问端口
    delay_loop 6                              # 健康检查时间
    lb_algo rr                                # 负载均衡调度算法,rr代表轮询
    lb_kind DR                                # 负载均衡转发规则 DR/NAT
    persistence_timeout 0                     # 会话保持时间,这里要做测试,所以设为0,实际可根据Session有效时间配置
    protocol TCP                              # 转发协议类型,支持TCP和UDP
    real_server 192.168.10.31 3306 {          # 配置服务器节点VIP1    
        notify_down /opt/mariaDB/mariadb.sh   # 当服务挂掉时,会执行此脚本,结束KeepAlived进程
        weight 1                              # 设置权重,越大权重越高
        TCP_CHECK {                           # 状态监测设置
            connect_timeout 10                # 超时配置,单位秒
            retry 3                           # 重试次数
            delay_before_retry 3              # 重试间隔
            connect_port 3306                 # 连接端口,和上面保持一致
        }
    }
}

注意配置项:

virtual_router_id 1234                    # 虚拟路由标示,同一个vrrp实例采用唯一标示
priority  100                             # 优先级,100代表最大优先级,数字越大优先级越高

b. 应用服务增加动态数据源

  1. 修改应用服务配置,增加新的数据源,指向新设置的 VIP:192.168.10.151
  2. 通过应用服务接口,动态扩容调整

c. 解除原双主模式

# 进入linux30
MariaDB [(none)]> stop slave;

# 进入linux31
MariaDB [(none)]> stop slave;

d. 安装 MariaDB 扩容服务器

(1)新建两台虚拟机,分别为 linux32 和 linux33

在 linux32 和 linux33 两台节点上安装 MariaDB 服务(参考上文-MariaDB 服务安装)

(2)配置 linux32 与 linux30 实现新的双主同步

# 1. 修改数据库配置
[root@linux32 ~]# vi /etc/my.cnf

[mysqld]
server-id=3
log-bin=mysql-bin
relay-log = mysql-relay-bin
replicate-wild-ignore-table=mysql.%
replicate-wild-ignore-table=information_schema.%
log-slave-updates=on
slave-skip-errors=all
auto-increment-offset=2
auto-increment-increment=2
binlog_format=mixed
expire_logs_days=10

# 2. 重启linux32数据库
[root@linux32 ~]# service mariadb restart

# 3. 创建replica用于主从同步的用户
[root@linux32 ~]# mysql -uroot -p123456
MariaDB [(none)]> grant replication slave, replication client on *.* to 'replica'@'%' identified by 'replica';
MariaDB [(none)]>  flush privileges;

# 4. 在linux30节点,进行数据全量备份
[root@linux30 mariaDB]# mysqldump -uroot -p123456 --routines --single_transaction --master-data=2 --databases smooth > linux30.sql

# 5. 查看并记录binlog信息
MariaDB [(none)]> show master status;
+------------------+----------+--------------+------------------+
| File             | Position | Binlog_Do_DB | Binlog_Ignore_DB |
+------------------+----------+--------------+------------------+
| mysql-bin.000003 |     1462 |              |                  |
+------------------+----------+--------------+------------------+
1 row in set (0.00 sec)

# 6. 将备份的linux30.sql通过scp命令拷贝至linux32节点
[root@linux30 mariaDB]# scp linux30.sql root@192.168.10.32:/opt/mariaDB

# 7. 将数据还原至linux32节点
[root@linux32 mariaDB]# mysql -uroot -p123456 < /opt/mariaDB/linux30.sql

# 8. 根据上面的master status信息配置主从同步信息,在linux32中执行:
MariaDB [(none)]> change master to master_host='192.168.10.30',master_user='replica', master_password='replica', master_port=3306, master_log_file='mysql-bin.000003', master_log_pos=1507, master_connect_retry=30;
Query OK, 0 rows affected (0.00 sec)

# 9. 开启主从同步(如果出现问题,通过 reset slave 复原主从同步信息)
MariaDB [(none)]>  start slave;
Query OK, 0 rows affected (0.00 sec)

# 10. 检查同步状态信息
MariaDB [(none)]> show slave status \G;
*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: 192.168.10.30
                  Master_User: replica
                  Master_Port: 3306
                Connect_Retry: 30
              Master_Log_File: mysql-bin.000003
          Read_Master_Log_Pos: 1462
               Relay_Log_File: mysql-relay-bin.000002
                Relay_Log_Pos: 555
        Relay_Master_Log_File: mysql-bin.000003
             Slave_IO_Running: Yes
            Slave_SQL_Running: Yes
...

# 11. 配置linux30与linux32节点的同步
# - 查看linux32的日志信息
MariaDB [(none)]>  show master status;
+------------------+----------+--------------+------------------+
| File             | Position | Binlog_Do_DB | Binlog_Ignore_DB |
+------------------+----------+--------------+------------------+
| mysql-bin.000001 |     2358 |              |                  |
+------------------+----------+--------------+------------------+
1 row in set (0.00 sec)
# - 在linux30节点,配置同步信息
MariaDB [(none)]> reset slave;
Query OK, 0 rows affected (0.00 sec)

MariaDB [(none)]> change master to master_host='192.168.10.32',master_user='replica', master_password='replica', master_port=3306, master_log_file='mysql-bin.000006', master_log_pos=1840, master_connect_retry=30;
Query OK, 0 rows affected (0.02 sec)

MariaDB [(none)]> start slave;
Query OK, 0 rows affected (0.00 sec)

(3)配置 linux33 与 linux31 的双主同步

同上大概一致。

e. 增加 KeepAlived 实现高可用

(1)确保新增的 linux32 和 linux33 节点安装 Keepalived 服务

(2)修改 linux32 / linux33 节点配置

[root@linux32 ~]# vi /etc/keepalived/keepalived.conf

global_defs {
   router_id linux30                          # 机器标识,和主机名保持一致,运行keepalived服务器的一个标识
}
vrrp_instance VI_1 {                          # vrrp实例定义
    state BACKUP                              # LVS的状态模式,MASTER代表主,BACKUP代表备份节点
    interface ens33                           # 绑定对外访问的网卡,vrrp实例绑定的网卡
    virtual_router_id 1234                    # 虚拟路由标示,同一个vrrp实例采用唯一标示
    priority 98                               # 优先级,100代表最大优先级,数字越大优先级越高
    advert_int 1                              # Master与Backup节点同步检查的时间间隔,单位是秒
    authentication {                          # 设置验证信息
        auth_type PASS                        # 有PASS和AH两种
        auth_pass 6666                        # 验证密码,BACKUP密码须相同
    }
    virtual_ipaddress {                       # KeepAlived虚拟的IP地址
        192.168.10.151
    }
}
virtual_server 192.168.10.151 3306 {          # 配置虚拟服务器IP与访问端口
    delay_loop 6                              # 健康检查时间
    lb_algo rr                                # 负载均衡调度算法,rr代表轮询
    lb_kind DR                                # 负载均衡转发规则 DR/NAT
    persistence_timeout 0                     # 会话保持时间,这里要做测试,所以设为0,实际可根据Session有效时间配置
    protocol TCP                              # 转发协议类型,支持TCP和UDP
    real_server 192.168.10.32 3306 {          # 配置服务器节点VIP1    
        notify_down /opt/mariaDB/mariadb.sh   # 当服务挂掉时,会执行此脚本,结束KeepAlived进程
        weight 1                              # 设置权重,越大权重越高
        TCP_CHECK {                           # 状态监测设置
            connect_timeout 10                # 超时配置,单位秒
            retry 3                           # 重试次数
            delay_before_retry 3              # 重试间隔
            connect_port 3306                 # 连接端口,和上面保持一致
        }
    }
}

创建关闭脚本 mariadb.sh:

[root@linux33 mariaDB]# vi /opt/mariaDB/mariadb.sh
## 添加脚本内容 ##
pkill keepalived
################
[root@linux33 mariaDB]# chmod a+x mariadb.sh

修改完后重启 Keepalived 服务。linux33 同理。

f. 清理数据并验证

  1. 通过应用服务动态扩容接口做调整和验证
  2. 在 linux30 节点清理数据(根据取模规则,保留 accountNo 为偶数的数据)
    delete from smooth.t_trade_order where accountNo % 2 != 0;
    
  3. 在 linux31 节点清理数据(根据取模规则,保留 accountNo 为奇数的数据)
    delete from smooth.t_trade_order where accountNo % 2 != 1;