文章目录
- [TiDB 数据库管控调研](#TiDB 数据库管控调研)
- 一、安装部署
- 二、数据库管理
-
- 数据库实例管理
- 运行状态监控
- 数据库备份与恢复
-
- 备份工具
- [全量备份(S3 自建 minio 备份桶)](#全量备份(S3 自建 minio 备份桶))
-
- [下载 minio 服务端 + mc 客户端](#下载 minio 服务端 + mc 客户端)
- 创建数据目录、运行用户
- [配置 systemd 自启服务](#配置 systemd 自启服务)
- 启动自启
- [使用 mc 连接 minio + 创建备份桶 backup-101(BR 要用的桶名)](#使用 mc 连接 minio + 创建备份桶 backup-101(BR 要用的桶名))
- [BR 备份 TiDB 完整可用命令(直接替换 MinIO 机器 IP 即可)](#BR 备份 TiDB 完整可用命令(直接替换 MinIO 机器 IP 即可))
- 恢复备份
- 补充
- 长久保留旧快照
- [日志备份与 PITR](#日志备份与 PITR)
- [使用 Dumpling 和 TiDB Lightning 备份与恢复](#使用 Dumpling 和 TiDB Lightning 备份与恢复)
-
- [获取 Dumpling 所需要的上游数据库权限](#获取 Dumpling 所需要的上游数据库权限)
- [获取 TiDB Lightning 所需要数据库的下游权限](#获取 TiDB Lightning 所需要数据库的下游权限)
- [使用 Dumpling 备份全量数据](#使用 Dumpling 备份全量数据)
- [使用 TiDB Lightning 恢复全量数据](#使用 TiDB Lightning 恢复全量数据)
- 三、数据高可用
TiDB 数据库管控调研
一、安装部署
数据库版本与操作系统选择
| 序号 | 主流版本 | 优先级 | 说明 |
|---|---|---|---|
| 1 | TiDB 8.5.x | 高 | 当前主流生产版本 |
| 2 | TiDB 8.1.x | 高 | 当前主流生产版本 |
| 3 | TiDB 7.5.x | 高 | 当前主流生产版本 |
| 4 | TiDB 7.1.x | 中 | 遗留系统仍在使用 |
| 5 | TiDB 6.5.x | 中 | 遗留系统仍在使用 |
| 序号 | 操作系统 | 适用版本 | 限制条件 |
|---|---|---|---|
| 1 | Rocky Linux 9.1+ | TiDB 7.x TiDB 8.x | |
| 2 | CentOS 7.3 及以上的 7.x 版本 | TiDB 6.x TiDB 7.x | CentOS Linux 7 的上游支持于 2024 年 6 月 30 日终止。从 8.4 DMR 版本开始,TiDB 已结束对 CentOS 7 的支持,建议使用 Rocky Linux 9.1 及以上的版本。 |
软件工具准备
离线部署 TiUP 组件时需要
| 软件包 | 版本 | 内部仓库路径 | 官方下载地址(备查) | 说明 |
|---|---|---|---|---|
| TiDB-community-server | v8.5.6 | /soft/tidb/tidb-community-server-v8.5.6-linux-amd64.tar.gz | https://pingkai.cn/download#tidb-community | TiDB 集群核心安装包,包含 PD、TiDB、TiKV、Prometheus、Grafana 等组件离线镜像 |
| TiDB-community-toolkit | v8.5.6 | /soft/tidb/tidb-community-toolkit-v8.5.6-linux-amd64.tar.gz | https://pingkai.cn/download#tidb-community | 包含 BR、TiCDC、TiUP Cluster、Ctl 等运维工具 |
| TiUP | v1.16.x | 集成于 Server 离线包 | https://tiup.io/?utm_source=chatgpt.com | TiDB 集群部署、升级、运维管理工具 |
| Prometheus | v8.5.6 配套版本 | 集成于 TiDB Server 包 | https://prometheus.io/?utm_source=chatgpt.com | 监控数据采集 |
| Grafana | v8.5.6 配套版本 | 集成于 TiDB Server 包 | https://grafana.com/?utm_source=chatgpt.com | 监控展示平台 |
| Alertmanager | v8.5.6 配套版本 | 集成于 TiDB Server 包 | https://prometheus.io/docs/alerting/latest/alertmanager/?utm_source=chatgpt.com | 告警管理组件 |
软件依赖项准备
依赖软件包清单
| 依赖 | 用途 | 安装方法 |
|---|---|---|
| numactl | NUMA 绑核工具的使用,主要为了防止 CPU 资源的争抢,引发性能衰退 | dnf -y install numactl |
| CTL(Control Tool Suite) | 集群控制与故障诊断工具 | tiup install ctl:v8.5.6 |
| Dumpling | 逻辑备份导出工具 | tiup install dumpling |
| TiDB Lightning | 高速数据导入工具 | tiup install tidb-lightning |
运行时所需的依赖库:glibc(2.28-151.el8 版本)【glibc >= 2.28】
安装命令:
bash
# 执行用户:root
dnf -y install numactl
# 执行用户:tidb
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs
source ~/.cargo/env
tiup install ctl:v8.5.6
tiup install dumpling
tiup install dumpling
配置操作系统参数
| 配置项 | 配置方法 | 建议值 | 说明 |
|---|---|---|---|
| 关闭防火墙 | systemctl stop firewalld && systemctl disable firewalld | ||
| 关闭 SELinux | sed -i "s/SELINUX = enforcing/SELINUX = disabled/" /etc/selinux/config getenforce | ||
| 关闭系统 swap | echo "vm.swappiness = 0" >> /etc/sysctl.conf swapoff -a && swapon -a sysctl -p | 运行 sysctl -p 生效 | |
| 关闭透明大页 | echo never > /sys/kernel/mm/transparent_hugepage/enabled | ||
| 修改 sysctl 内存参数 | 修改/etc/sysctl.conf | fs.file-max = 1000000 net.core.somaxconn = 32768 net.ipv4.tcp_syncookies = 0 vm.overcommit_memory = 1 vm.min_free_kbytes = 1048576 | 运行 sysctl -p 生效 |
| 修改资源限制(limits.conf) | 修改/etc/security/limits.conf | tidb soft nofile 1000000 tidb hard nofile 1000000 tidb soft stack 32768 tidb hard stack 32768 | |
| 配置时区 | timedatectl set-timezone Asia/Shanghai | ||
| 配置字符集 | 修改/etc/locale.conf | LANG = en_US.UTF-8 |
bash
# [执行用户:root]
# 关闭防火墙
systemctl stop firewalld && systemctl disable firewalld
#关闭系统swap
echo "vm.swappiness = 0">> /etc/sysctl.conf
swapoff -a && swapon -a
sysctl -p
# 关闭透明大页
echo never > /sys/kernel/mm/transparent_hugepage/enabled
# 修改内存参数
echo "fs.file-max = 1000000">> /etc/sysctl.conf
echo "net.core.somaxconn = 32768">> /etc/sysctl.conf
echo "net.ipv4.tcp_syncookies = 0">> /etc/sysctl.conf
echo "vm.overcommit_memory = 1">> /etc/sysctl.conf
echo "vm.min_free_kbytes = 1048576">> /etc/sysctl.conf
sysctl -p
# 修改资源限制(limits.conf)
cat << EOF >>/etc/security/limits.conf
tidb soft nofile 1000000
tidb hard nofile 1000000
tidb soft stack 32768
tidb hard stack 32768
EOF
#配置时区
timedatectl set-timezone Asia/Shanghai
#配置字符集
cat >> /etc/locale.conf <<'EOF'
LANG=en_US.UTF-8
EOF
创建用户和目录
用户信息:
| 项目 | 值 |
|---|---|
| 用户组名 | tidb |
| 组 ID (GID) | 1000 |
| 用户名 | tidb |
| 用户 ID (UID) | 1000 |
| Home 目录 | /home/tidb |
# [执行用户:root]
# 创建用户组和用户
groupadd -g 1000 tidb
useradd -u 1000 -g 1000 tidb
目录规划
| 目录 | 路径 | 用途 | 属主 |
|---|---|---|---|
| Tiup工具目录 | ~/.tiup/components/ | 存放像Dumpling工具位置 | tidb |
| 软件安装目录 | /opt/software/ | 软件目录 | tidb |
| 数据目录 | /data/tidbdata | 数据 | tidb |
| 日志目录 | ~/.tiup/logs | 日志位置 | tidb |
| 配置文件目录 | ~/.tiup/ | 配置文件位置 | tidb |
单机版本安装详细步骤
步骤一:安装数据库软件
bash
# 执行用户:tidb
# 下载并安装
curl --proto '=https' --tlsv1.2 -sSf https://tiup-mirrors.pingcap.com/install.sh | sh
sudo dnf -y install numactl
tiup install ctl:v8.5.6
# 声明全局环境变量
source /home/tidb/.bash_profile
# 安装 TiUP 的 cluster 组件
tiup cluster
#如果机器已经安装 TiUP cluster,需要更新软件版本
tiup update --self && tiup update cluster
# 通过 root 用户调大 sshd 服务的连接数限制
cat << EOF >> /etc/ssh/sshd_config
MaxSessions 20
EOF
# 重启sshd服务
service sshd restart
# 后续用tidb用户
# 创建数据文件目录
sudo mkdir -p /data/tidbdata
sudo mkdir /tibd-deploy
安装验证:
bash
# 确认安装成功
[tidb@nzl-ti tidb]$ curl --proto '=https' --tlsv1.2 -sSf https://tiup-mirrors.pingcap.com/install.sh | sh
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 4709k 100 4709k 0 0 3816k 0 0:00:01 0:00:01 --:--:-- 3816k
Successfully set mirror to https://tiup-mirrors.pingcap.com
Detected shell: bash
Shell profile: /home/tidb/.bash_profile
/home/tidb/.bash_profile has been modified to add tiup to PATH
open a new terminal or source /home/tidb/.bash_profile to use it
Installed path: /home/tidb/.tiup/bin/tiup
===============================================
Have a try: tiup playground
===============================================
[tidb@nzl-ti tidb]$ ls -la /home/tidb/
总用量 12
drwx------ 3 tidb tidb 75 6月 2 11:29 .
drwxr-xr-x. 3 root root 18 6月 2 11:26 ..
-rw-r--r-- 1 tidb tidb 18 4月 30 2024 .bash_logout
-rw-r--r-- 1 tidb tidb 181 6月 2 11:29 .bash_profile
-rw-r--r-- 1 tidb tidb 492 4月 30 2024 .bashrc
drwxr-xr-x 3 tidb tidb 34 6月 2 11:29 .tiup
# 获取数据库版本(可以查看版本号)
[tidb@nzl-ti bin]$ ./tiup list tidb
Available versions for tidb:
Version Installed Release Platforms
------- --------- ------- ---------
nightly -> v9.0.0-beta.2.pre-nightly 2026-06-02T03:59:02Z ......
......
darwin/amd64,darwin/arm64,linux/amd64,linux/arm64
v7.5.7 2025-09-04T04:54:43Z darwin/amd64,darwin/arm64,linux/amd64,linux/arm64
v7.6.0 2024-01-25T04:29:14Z darwin/amd64,darwin/arm64,linux/amd64,linux/arm64
v8.0.0 2024-03-29T04:28:29Z darwin/amd64,darwin/arm64,linux/amd64,linux/arm64
......
......
#查看bin目录位置
[tidb@nzl-ti bin]$ ll /home/tidb/.tiup/
总用量 4
drwxr-xr-x 2 tidb tidb 69 6月 2 11:29 bin
drwxr-xr-x 2 tidb tidb 28 6月 2 11:33 history
drwxr-xr-x 2 tidb tidb 177 6月 2 11:33 manifests
-rw-r--r-- 1 tidb tidb 44 6月 2 11:29 tiup.toml
步骤二:编写配置文件
配置文件路径: /home/tidb/topo.yaml
配置文件如下:
bash
# # Global variables are applied to all deployments and used as the default value of
# # the deployments if a specific deployment value is missing.
global:
user: "tidb"
ssh_port: 22
deploy_dir: "/tidb-deploy"
data_dir: "/data/tidbdata"
# # Monitored variables are applied to all the machines.
monitored:
node_exporter_port: 9100
blackbox_exporter_port: 9115
server_configs:
tidb:
instance.tidb_slow_log_threshold: 300
tikv:
readpool.storage.use-unified-pool: false
readpool.coprocessor.use-unified-pool: true
pd:
replication.enable-placement-rules: true
replication.location-labels: ["host"]
tiflash:
logger.level: "info"
pd_servers:
- host: 10.197.167.110
tidb_servers:
- host: 10.197.167.110
tikv_servers:
- host: 10.197.167.110
port: 20160
status_port: 20180
config:
server.labels: { host: "logic-host-1" }
- host: 10.197.167.110
port: 20161
status_port: 20181
config:
server.labels: { host: "logic-host-2" }
- host: 10.197.167.110
port: 20162
status_port: 20182
config:
server.labels: { host: "logic-host-3" }
tiflash_servers:
- host: 10.197.167.110
monitoring_servers:
- host: 10.197.167.110
grafana_servers:
- host: 10.197.167.110
user: "tidb":表示通过tidb系统用户(部署会自动创建)来做集群的内部管理,默认使用 22 端口通过 ssh 登录目标机器replication.enable-placement-rules:设置这个 PD 参数来确保 TiFlash 正常运行host:设置为本部署主机的 IP
步骤三:初始化数据库
执行初始化
bash
# tiup cluster deploy <cluster-name> <version> ./topo.yaml --user root -p
tiup cluster deploy tidb_test v8.5.6 /home/tidb/topo.yaml --user root -p
...
Enabling component node_exporter
Enabling instance 10.197.167.110
download https://tiup-mirrors.pingcap.com/tikv-v8.5.6-linux-amd64.tar.gz 0 B / 376.95 MiB 0.00% ? MiB/s Enable 10.197.167.110 success
Enabling component blackbox_exporter
Enabling instance 10.197.167.110
download https://tiup-mirrors.pingcap.com/tikv-v8.5.6-linux-amd64.tar.gz 0 B / 376.95 MiB 0.00% ? MiB/s Enable 10.197.167.110 success
Cluster `tidb_test` deployed successfully, you can start it with command: `tiup cluster start tidb_test --init`
tiup cluster deploy <cluster-name> <version> ./topo.yaml --user root -p
其中 cluster-name 代表的集群名称,version 使用版本
步骤四:启动数据库并验证
# 启动(tidb_test是集群名称)
tiup cluster start tidb_test --init
生成密码:X95+y3j6J_27AsU^@u
# 验证连接(查看集群的拓扑结构和状态)
[tidb@nzl-ti ~]$ tiup cluster display tidb_test
Cluster type: tidb
Cluster name: tidb_test
Cluster version: v8.5.6
Deploy user: tidb
SSH type: builtin
Dashboard URL: http://10.197.167.110:2379/dashboard
Dashboard URLs: http://10.197.167.110:2379/dashboard
Grafana URL: http://10.197.167.110:3000
ID Role Host Ports OS/Arch Status Data Dir Deploy Dir
-- ---- ---- ----- ------- ------ -------- ----------
10.197.167.110:3000 grafana 10.197.167.110 3000 linux/x86_64 Up - /tidb-deploy/grafana-3000
10.197.167.110:2379 pd 10.197.167.110 2379/2380 linux/x86_64 Up|L|UI /data/tidbdata/pd-2379 /tidb-deploy/pd-2379
10.197.167.110:9090 prometheus 10.197.167.110 9090/9115/9100/12020 linux/x86_64 Up /data/tidbdata/prometheus-9090 /tidb-deploy/prometheus-9090
10.197.167.110:4000 tidb 10.197.167.110 4000/10080 linux/x86_64 Up - /tidb-deploy/tidb-4000
10.197.167.110:9000 tiflash 10.197.167.110 9000/3930/20170/20292/8234/8123 linux/x86_64 Up /data/tidbdata/tiflash-9000 /tidb-deploy/tiflash-9000
10.197.167.110:20160 tikv 10.197.167.110 20160/20180 linux/x86_64 Up /data/tidbdata/tikv-20160 /tidb-deploy/tikv-20160
10.197.167.110:20161 tikv 10.197.167.110 20161/20181 linux/x86_64 Up /data/tidbdata/tikv-20161 /tidb-deploy/tikv-20161
10.197.167.110:20162 tikv 10.197.167.110 20162/20182 linux/x86_64 Up /data/tidbdata/tikv-20162 /tidb-deploy/tikv-20162
Total nodes: 8
# 连接方式
# 本地安装mysql客户端
sudo dnf install mysql
# 连接(默认没有密码),使用--init会生成密码
mysql -h 10.197.167.110 -P 4000 -u root
二、数据库管理
数据库实例管理
启动和关闭
启动
# 全集群启动(首次必加 --init 生成 root 密码)
iup cluster start tidb_test --init
X95+y3j6J_27AsU^@u
# 后续日常重启,不用--init
tiup cluster start tidb_test
关闭
tiup cluster stop tidb_test
systemd service 文件:
bash
# /etc/systemd/system/tidb-4000.service
[Unit]
Description=tidb service
After=syslog.target network.target remote-fs.target nss-lookup.target
[Service]
LimitNOFILE=1000000
LimitSTACK=10485760
User=tidb
ExecStart=/bin/bash -c '/tidb-deploy/tidb-4000/scripts/run_tidb.sh'
Restart=always
RestartSec=15s
[Install]
WantedBy=multi-user.target
# /etc/systemd/system/tiflash-9000.service
[Unit]
Description=tiflash service
After=syslog.target network.target remote-fs.target nss-lookup.target
[Service]
LimitNOFILE=1000000
LimitSTACK=10485760
User=tidb
ExecStart=/bin/bash -c '/tidb-deploy/tiflash-9000/scripts/run_tiflash.sh'
Restart=always
RestartSec=15s
[Install]
WantedBy=multi-user.target
# /etc/systemd/system/tikv-20160.service
[Unit]
Description=tikv service
After=syslog.target network.target remote-fs.target nss-lookup.target
[Service]
LimitNOFILE=1000000
LimitSTACK=10485760
User=tidb
ExecStart=/bin/bash -c '/tidb-deploy/tikv-20160/scripts/run_tikv.sh'
Restart=always
RestartSec=15s
[Install]
WantedBy=multi-user.target
# /etc/systemd/system/tikv-20161.service
[Unit]
Description=tikv service
After=syslog.target network.target remote-fs.target nss-lookup.target
[Service]
LimitNOFILE=1000000
LimitSTACK=10485760
User=tidb
ExecStart=/bin/bash -c '/tidb-deploy/tikv-20161/scripts/run_tikv.sh'
Restart=always
RestartSec=15s
[Install]
WantedBy=multi-user.target
# /etc/systemd/system/tikv-20162.service
[Unit]
Description=tikv service
After=syslog.target network.target remote-fs.target nss-lookup.target
[Service]
LimitNOFILE=1000000
LimitSTACK=10485760
User=tidb
ExecStart=/bin/bash -c '/tidb-deploy/tikv-20162/scripts/run_tikv.sh'
Restart=always
RestartSec=15s
[Install]
WantedBy=multi-user.target
[root@nzl-ti system]#
判断运行状态
# 方式一:PID 文件(pid 文件路径:/tidb-deploy/,格式:**-id)
[root@nzl-ti ~]# cd /tidb-deploy/
[root@nzl-ti tidb-deploy]# ll
total 0
drwxr-xr-x. 10 tidb tidb 120 Jun 2 15:50 grafana-3000
drwxr-xr-x. 6 tidb tidb 55 Jun 2 15:49 monitor-9100
drwxr-xr-x. 6 tidb tidb 55 Jun 2 15:48 pd-2379
drwxr-xr-x. 6 tidb tidb 55 Jun 2 15:49 prometheus-9090
drwxr-xr-x. 6 tidb tidb 55 Jun 2 15:48 tidb-4000
drwxr-xr-x. 6 tidb tidb 55 Jun 2 15:49 tiflash-9000
drwxr-xr-x. 6 tidb tidb 55 Jun 2 15:48 tikv-20160
drwxr-xr-x. 6 tidb tidb 55 Jun 2 15:48 tikv-20161
drwxr-xr-x. 6 tidb tidb 55 Jun 2 15:48 tikv-20162
# 方式二:进程检查
# 查TiDB进程
ps -ef | grep tidb-server | grep -v grep
# 查PD进程
ps -ef | grep pd-server | grep -v grep
# 查TiKV进程
ps -ef | grep tikv-server | grep -v grep
# 方式三:端口检查
[root@nzl-ti ~]# ss -tlnp | grep -E "4000|2379|20160"
LISTEN 0 32768 *:2379 *:* users:(("pd-server",pid=902,fd=7))
LISTEN 0 32768 *:20160 *:* users:(("tikv-server",pid=920,fd=124))
LISTEN 0 32768 *:20160 *:* users:(("tikv-server",pid=920,fd=127))
LISTEN 0 32768 *:20160 *:* users:(("tikv-server",pid=920,fd=128))
LISTEN 0 32768 *:20160 *:* users:(("tikv-server",pid=920,fd=129))
LISTEN 0 32768 *:20160 *:* users:(("tikv-server",pid=920,fd=130))
LISTEN 0 32768 *:4000 *:* users:(("tidb-server",pid=913,fd=27))
# 方式四:数据库自带命令
mysql -h10.197.167.110 -P4000 -uroot -p
-- 查看实例运行时长
SHOW STATUS LIKE 'Uptime';
-- 查看数据库版本
SELECT VERSION();
-- 查看在线连接
SHOW PROCESSLIST;
# 查看集群的拓扑结构和状态
tiup cluster display tidb_test
数据库参数设置
# 以编辑模式打开该集群的配置文件
tiup cluster edit-config tidb_test
# SQL 系统变量
-- 查看变量
SHOW GLOBAL VARIABLES LIKE 'tidb_%';
SHOW SESSION VARIABLES LIKE 'sql_mode';
-- 设置全局变量(新会话生效,持久化到存储)
SET GLOBAL tidb_mem_quota_query = 1073741824; -- 1GB查询内存限制
SET GLOBAL tidb_enable_async_commit = ON; -- 开启异步提交
-- 设置会话变量(仅当前连接生效)
SET SESSION autocommit = 0;
# SETCONFIG
-- 修改所有TiKV实例的分裂QPS阈值
SET CONFIG tikv `split.qps-threshold` = 1000; {insert\_element\_2\_}
-- 修改单个TiKV实例的参数(指定IP:端口)
SET CONFIG '10.197.167.110:20160' `storage.block-cache.capacity` = '16GB'; {insert\_element\_3\_}
-- 修改PD集群的调度周期
SET CONFIG pd `schedule.leader-schedule-limit` = 4;
运行状态监控
会话管理
查看当前所有会话
mysql> SHOW FULL PROCESSLIST;
+------------+------+----------------------+------+---------+------+------------+-----------------------+
| Id | User | Host | db | Command | Time | State | Info |
+------------+------+----------------------+------+---------+------+------------+-----------------------+
| 3397386246 | root | 10.197.167.110:54952 | NULL | Query | 0 | autocommit | SHOW FULL PROCESSLIST |
+------------+------+----------------------+------+---------+------+------------+-----------------------+
1 row in set (0.01 sec)
终止会话/查询
-- 终止查询(保留连接)
KILL QUERY 3397386246;
-- 终止会话(断开连接)
KILL CONNECTION 3397386246;
锁管理
# 查看锁等待
SELECT * FROM information_schema.data_lock_waits;
# 查看阻塞关系(持有锁会话、等待锁会话)
SELECT * FROM information_schema.data_locks;
-- 关联查看完整阻塞链路
SELECT r.TRX_ID 阻塞事务ID,r.SESSION_ID 阻塞会话ID,w.TRX_ID 等待事务ID,w.SESSION_ID 等待会话ID
FROM information_schema.data_locks r
JOIN information_schema.data_lock_waits w ON r.TRX_ID = w.BLOCKING_TRX_ID;
# 终止锁 / 回滚事务(两种方式)
# kill阻塞会话
KILL 阻塞会话ID;
#终止指定事务
KILL TIDB [事务ID];
# 查询正在运行的长事务
SELECT * FROM information_schema.innodb_trx;
其他常用监控 SQL
数据库大小统计
-- 全库总容量(单位Byte)
SELECT SUM(SCHEMA_SIZE) AS total_size_byte, SUM(SCHEMA_SIZE)/1024/1024/1024 AS total_size_gb
FROM information_schema.tidb_schema_size;
-- 逐个库占用空间
SELECT TABLE_SCHEMA, SUM(SCHEMA_SIZE)/1024/1024 AS size_mb
FROM information_schema.tidb_schema_size
GROUP BY TABLE_SCHEMA ORDER BY size_mb DESC;
表大小统计(Top N)
-- 占用空间TOP20大表
SELECT TABLE_SCHEMA,TABLE_NAME,TABLE_SIZE/1024/1024 AS table_mb
FROM information_schema.tidb_table_size
ORDER BY TABLE_SIZE DESC LIMIT 20;
慢 SQL 统计
-- 查看近期慢日志(默认超过300ms记录)
SELECT * FROM INFORMATION_SCHEMA.SLOW_QUERY
WHERE Query_time > 1
ORDER BY Query_time DESC LIMIT 50;
-- 按SQL聚合耗时、执行次数
SELECT DIGEST_TEXT,COUNT(*) exec_cnt,SUM(Query_time) total_cost
FROM INFORMATION_SCHEMA.SLOW_QUERY
GROUP BY DIGEST_TEXT ORDER BY total_cost DESC LIMIT 30;
查看执行计划
-- 基础执行计划
EXPLAIN SELECT * FROM 表名 WHERE 条件;
-- 详细真实执行开销(含运行数据)
EXPLAIN ANALYZE SELECT * FROM 表名 WHERE 条件;
用户管理
sql
-- 查看所有用户
SELECT user,host FROM mysql.user;
-- 创建用户
CREATE USER 'test'@'%' IDENTIFIED '123456';
-- 修改密码
ALTER USER 'test'@'%' IDENTIFIED BY '新密码';
-- 授权
GRANT SELECT,INSERT,UPDATE,DELETE ON testdb.* TO 'test'@'%';
-- 全库全权限
GRANT ALL PRIVILEGES ON *.* TO 'test'@'%';
-- 撤销权限
REVOKE INSERT,UPDATE ON testdb.* FROM 'test'@'%';
-- 删除用户
DROP USER 'test'@'%';
常用权限清单
| 权限 | 说明 | 使用场景 |
|---|---|---|
| ALL PRIVILEGES | 所有权限,除 GRANT OPTION | DBA 管理员账号、开发管理账号 |
| SELECT | 查询数据 | 普通业务只读账号、报表账号 |
| INSERT | 新增数据 | 业务写入账号 |
| UPDATE | 更新已有数据 | 业务正常更新数据 |
| DELETE | 删除表数据 | 业务删数、运维清理数据 |
| CREATE | 创建库、数据表 | 项目初期建库建表 |
| DROP | 删除库、数据表 | 运维删库删表,谨慎分配 |
| ALTER | 修改表结构(加字段、改字段) | DDL 变更、迭代改表 |
| INDEX | 创建 / 删除索引 | 业务新增、删除索引优化查询 |
| CREATE VIEW | 创建视图 | 报表业务封装视图 |
| DROP VIEW | 删除视图 | 废弃报表清理视图 |
| PROCESS | 查看全量 processlist、锁信息 | DBA 排查会话、阻塞 |
| GRANT OPTION | 把自身拥有的权限授权给别的用户 | 次级管理员账号 |
数据库备份与恢复
备份工具
备份工具名称: BR
备份工具安装包内部仓库路径: ~/root/.tiup/components/br
安装方法
tiup install br
[tidb@nzl-ti ~]# tiup install br
download https://tiup-mirrors.pingcap.com/br-v8.5.6-linux-amd64.tar.gz 105.12 MiB / 105.12 MiB 100.00% 40.47 MiB/s
以及使用 Dumpling 和 TiDB Lightning 备份与恢复(如果需要备份大量数据,建议使用 BR)
tiup install dumpling
tiup install tidb-lightning
备份工具安装包内部仓库路径: ~/root/.tiup/components/dumpling ~/root/.tiup/components/tidb-ligthning
全量备份(S3 自建 minio 备份桶)
# 对集群进行快照备份
tiup br backup full --pd "${PD_IP}:2379" \
--backupts '2022-09-08 13:30:00 +08:00' \
--storage "s3://backup-101/snapshot-202209081330?access-key=${access-key}&secret-access-key=${secret-access-key}" \
# 恢复tiup br restore
tiup br restore full --pd "${PD_IP}:2379" \
--storage "s3://backup-101/snapshot-202209081330?access-key=${access-key}&secret-access-key=${secret-access-key}" \
-
--backupts:快照对应的物理时间点,格式可以是 TSO 或者时间戳,例如400036290571534337或者2018-05-11 01:42:23 +08:00。如果该快照的数据被垃圾回收 (GC) 了,那么tiup br backup命令会报错并退出。使用日期方式备份时,建议同时指定时区,否则 br 默认使用本地时间构造时间戳,可能导致备份时间点错误。如果你没有指定该参数,那么 br 会选取备份开始的时间点所对应的快照。 -
--storage:数据备份到的存储地址。快照备份支持以 Amazon S3、Google Cloud Storage、Azure Blob Storage 为备份存储,以上命令以 Amazon S3 为示例。详细存储地址格式请参考 外部存储服务的 URI 格式。 -
full:用于备份或恢复整个备份数据。 -
db:用于备份或恢复集群中的指定数据库。 -
table:用于备份或恢复集群指定数据库中的单张表。
https://docs.pingcap.com/zh/tidb/stable/use-br-command-line-tool/
搭建 MinIO 作为备份存储系统,使用 S3 协议数据备份到 MinIO 中
下载 minio 服务端 + mc 客户端
#下载minio二进制
wget https://dl.min.io/server/minio/release/linux-amd64/minio -O /opt/software/minio
chmod +x /opt/software/minio
#下载mc管理客户端
wget https://dl.min.io/client/mc/release/linux-amd64/mc -O /opt/software/mc
chmod +x /opt/software/mc
#验证版本
minio --version
mc --version
创建数据目录、运行用户
#创建存储目录(备份数据存这里)
mkdir -p /data/miniodata
#创建专用运行用户
useradd minio
chown -R minio:minio /data/miniodata
配置 systemd 自启服务
cat > /etc/systemd/system/minio.service <<EOF
[Unit]
Description=MinIO
Documentation=https://docs.min.io
Wants=network-online.target
After=network-online.target
[Service]
User=minio
Group=minio
#minio账号密码
Environment="MINIO_ROOT_USER=minioadmin"
Environment="MINIO_ROOT_PASSWORD=minioadmin"
#数据目录+端口
ExecStart=/opt/software/minio server /data/miniodata --address :9000 --console-address :9001
Restart=on-failure
LimitNOFILE=65536
[Install]
WantedBy=multi-user.target
EOF
Environment = "MINIO_ROOT_USER = minioadmin"
Environment = "MINIO_ROOT_PASSWORD = minioadmin"
密钥
启动自启
systemctl daemon-reload
systemctl start minio
systemctl enable minio
systemctl status minio
使用 mc 连接 minio + 创建备份桶 backup-101(BR 要用的桶名)
#配置别名,格式 mc alias set 别名 http://ip:9000 AK SK
mc alias set minio-cluster http://10.197.167.110:9000 minioadmin minioadmin
#查看连通
mc ls minio-cluster
#创建桶 backup-101(必须和BR命令里桶名一致)
mc mb minio-cluster/backup-101
#确认桶存在
mc ls minio-cluster
BR 备份 TiDB 完整可用命令(直接替换 MinIO 机器 IP 即可)
tiup br backup full --pd "10.197.167.110:2379" \
--backupts '2026-06-03 10:41:00 +08:00' \
--storage "s3://backup-101/snapshot-20260603?access-key=minioadmin&secret-access-key=minioadmin" \
--s3.endpoint=http://10.197.167.110:9000 \
--s3.provider=minio
# 运行情况
Starting component br: /root/.tiup/components/br/v8.5.6/br backup full --pd 10.197.167.110:2379 --backupts 2026-06-03 10:41:00 +08:00 --storage s3://backup-101/snapshot-20260603?access-key=%2A%2A%2A%2A%2A%2A&secret-access-key=%2A%2A%2A%2A%2A%2A --s3.endpoint=http://10.197.167.110:9000 --s3.provider=minio
Detail BR log in /tmp/br.log.2026-06-03T10.41.26+0800
Full Backup <----------------------------------------------------------------------------------------------------> 100.00%
Checksum <............................................................................................................> ?%
[2026/06/03 10:41:30.923 +08:00] [INFO] [collector.go:77] ["Full Backup success summary"] [total-ranges=20] [ranges-succeed=20] [ranges-failed=0] [backup-checksum=73.676368ms] [backup-total-regions=141] [write-CF-files=19] [default-CF-files=1] [backup-total-ranges=141] [total-take=4.168222296s] [BackupTS=466735453962240000] [total-kv=1507] [total-kv-size=460.3kB] [average-speed=110.4kB/s] [backup-data-size(after-compressed)=114.9kB] [Size=114941]
在快照备份过程中,终端会显示备份进度条。在备份完成后,会输出备份耗时、速度、备份数据大小等信息。其中:
total-ranges:备份的文件总数量ranges-succeed:备份成功的文件数量ranges-failed:备份失败的文件数量backup-total-ranges:备份的表(包括分区表)与索引的数量write-CF-files:备份文件中含有write CF数据的 SST 文件数量default-CF-files:备份文件中含有default CF数据的 SST 文件数量
恢复备份
tiup br restore full --pd "10.197.167.110:2379" \
--with-sys-table \
--storage "s3://backup-101/snapshot-20260603?access-key=minioadmin&secret-access-key=minioadmin" \
--s3.endpoint=http://10.197.167.110:9000 \
--s3.provider=minio
# 可以加--ratelimit:每个 TiKV 执行恢复任务的速度上限(单位 MiB/s)。
# --with-sys-table:恢复集群数据的同时恢复部分系统表的数据,包括恢复账号权限数据、 SQL Binding 信息和统计信息数据,但暂不支持恢复统计信息表 (mysql.stat_*) 和系统参数 (mysql.tidb, mysql.global_variables) 等信息
# 从 TiDB v8.5.5 开始,你可以通过指定参数 --fast-load-sys-tables 在全新的集群上进行物理恢复系统表:
tiup br restore full \
--pd "${PD_IP}:2379" \
--with-sys-table \
--fast-load-sys-tables \
--storage "s3://${backup_collection_addr}/snapshot-${date}?access-key=${access-key}&secret-access-key=${secret-access-key}" \
--ratelimit 128 \
--log-file restorefull.log
恢复示例
# 删除表
mysql> use test;
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> show tables;
+----------------+
| Tables_in_test |
+----------------+
| t1 |
+----------------+
1 row in set (0.00 sec)
mysql> drop tables t1;
Query OK, 0 rows affected (0.31 sec)
mysql> show tables;
Empty set (0.00 sec)
# 执行备份恢复
[root@nzl-ti software]# tiup br restore full --pd "10.197.167.110:2379" \
--storage "s3://backup-101/snapshot-20260603?access-key=minioadmin&secret-access-key=minioadmin" \
--s3.endpoint=http://10.197.167.110:9000 \
--s3.provider=minio
Starting component br: /root/.tiup/components/br/v8.5.6/br restore full --pd 10.197.167.110:2379 --storage s3://backup-101/snapshot-20260603?access-key=%2A%2A%2A%2A%2A%2A&secret-access-key=%2A%2A%2A%2A%2A%2A --s3.endpoint=http://10.197.167.110:9000 --s3.provider=minio
Detail BR log in /tmp/br.log.2026-06-03T10.45.58+0800
Split&Scatter Regions <------------------------------------------------------------------------------------------> 100.00%
Download&Ingest SST <--------------------------------------------------------------------------------------------> 100.00%
Restore Pipeline <-----------------------------------------------------------------------------------------------> 100.00%
[2026/06/03 10:46:05.298 +08:00] [INFO] [collector.go:77] ["Full Restore success summary"] [total-ranges=7] [ranges-succeed=7] [ranges-failed=0] [merge-ranges=208.995µs] [split-regions=67.814069ms] [restore-files=374.721578ms] [restore-pipeline=573.542043ms] [default-CF-files=0] [write-CF-files=7] [split-keys=1] [total-take=6.885125312s] [Size=22437] [BackupTS=466735453962240000] [RestoreTS=466735532281430017] [total-kv=8] [total-kv-size=697B] [average-speed=101.2B/s] [restore-data-size(after-compressed)=22.44kB]
# 查看是否恢复
mysql> use test;
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> show tables;
+----------------+
| Tables_in_test |
+----------------+
| t1 |
+----------------+
1 row in set (0.00 sec)
mysql> select * from t1;
+----+--------+-------------+
| id | name | phone |
+----+--------+-------------+
| 1 | 小张 | 12323458930 |
| 2 | 小红 | 18376258930 |
+----+--------+-------------+
2 rows in set (0.00 sec)
补充
# 备份集群快照
tiup br backup full --pd "10.197.167.110:2379" \
--backupts '2026-06-03 10:41:00 +08:00' \
--storage "s3://backup-101/snapshot-20260603?access-key=minioadmin&secret-access-key=minioadmin" \
--s3.endpoint=http://10.197.167.110:9000 \
--s3.provider=minio
# 恢复集群快照
tiup br restore full --pd "10.197.167.110:2379" \
--storage "s3://backup-101/snapshot-20260603?access-key=minioadmin&secret-access-key=minioadmin" \
--s3.endpoint=http://10.197.167.110:9000 \
--s3.provider=minio
# 备份单个数据库(--backupts没有=当前时间打快照)
tiup br backup db --pd "10.197.167.110:2379" \
--db test \
--storage "s3://backup-101/snapshot-20260603?access-key=minioadmin&secret-access-key=minioadmin" \
--s3.endpoint=http://10.197.167.110:9000 \
--s3.provider=minio
# 备份单张表(--log-file将备份日志写入的目标文件)
tiup br backup db --pd "10.197.167.110:2379" \
--db test \
--table t1 \
--storage "s3://backup-101/snapshot-20260603?access-key=minioadmin&secret-access-key=minioadmin" \
--log-file backuptable.log \
--s3.endpoint=http://10.197.167.110:9000 \
--s3.provider=minio
# 备份多个表(*通配符:数据库.表)
tiup br backup db --pd "10.197.167.110:2379" \
--filter 'db*.tbl*' \
--storage "s3://backup-101/snapshot-20260603?access-key=minioadmin&secret-access-key=minioadmin" \
--log-file backuptable.log \
--s3.endpoint=http://10.197.167.110:9000 \
--s3.provider=minio
长久保留旧快照
#延长GC保留时长(例如24h)
SET GLOBAL tidb_gc_life_time = '24h';
# 默认10m十分钟
mysql> SHOW GLOBAL VARIABLES LIKE 'tidb_gc_life_time';
+-------------------+-------+
| Variable_name | Value |
+-------------------+-------+
| tidb_gc_life_time | 10m0s |
+-------------------+-------+
1 row in set (0.00 sec)
# 查看GC安全点(可访问的最早快照时间)
SELECT VARIABLE_VALUE AS gc_safepoint
FROM mysql.tidb
WHERE VARIABLE_NAME = 'tikv_gc_safe_point';
日志备份与 PITR
执行 tiup br log start 命令启动日志备份任务,一个集群只能启动一个日志备份任务。
tiup br log start --task-name=pitr --pd "10.197.167.110:2379" \
--storage 's3://backup-101/logbackup?access-key=minioadmin&secret-access-key=minioadmin' \
--s3.endpoint=http://10.197.167.110:9000 \
--s3.provider=minio
# 运行结果
Starting component br: /root/.tiup/components/br/v8.5.6/br log start --task-name=pitr --pd 10.197.167.110:2379 --storage s3://backup-101/logbackup?access-key=%2A%2A%2A%2A%2A%2A&secret-access-key=%2A%2A%2A%2A%2A%2A --s3.endpoint=http://10.197.167.110:9000 --s3.provider=minio
Detail BR log in /tmp/br.log.2026-06-03T13.55.45+0800
[2026/06/03 13:55:45.619 +08:00] [INFO] [collector.go:77] ["log start"] [streamTaskInfo="{taskName=pitr,startTs=466738517263777794,endTS=999999999999999999,tableFilter=*.*}"] [pausing=false] [rangeCount=2]
[2026/06/03 13:55:45.621 +08:00] [INFO] [collector.go:77] ["log start success summary"] [total-ranges=0] [ranges-succeed=0] [ranges-failed=0] [total-take=61.940703ms]
查询日志备份状态
tiup br log status --task-name=pitr --pd "10.197.167.110:2379"
# 查询结果
Starting component br: /root/.tiup/components/br/v8.5.6/br log status --task-name=pitr --pd 10.197.167.110:2379
Detail BR log in /tmp/br.log.2026-06-03T13.56.30+0800
● Total 1 Tasks.
> #1 <
name: pitr
status: ● NORMAL
start: 2026-06-03 13:55:45.568 +0800
end: 2090-11-18 22:07:45.624 +0800
storage: s3://backup-101/logbackup
speed(est.): 0.00 ops/s
checkpoint[global]: 2026-06-03 13:55:45.568 +0800; gap=46s
定期执行全量备份
tiup br backup full --pd "10.197.167.110:2379" \
--storage 's3://backup-101/snapshot-202606031405?access-key=minioadmin&secret-access-key=minioadmin' \
--s3.endpoint=http://10.197.167.110:9000 \
--s3.provider=minio
进行 PITR
如果你想恢复到备份保留期内的任意时间点,可以使用 tiup br restore point 命令。执行该命令时,你需要指定 要恢复的时间点 、恢复时间点之前最近的快照备份 以及 日志备份数据。br 命令行工具会自动判断和读取恢复需要的数据,然后将这些数据依次恢复到指定的集群。
tiup br restore point --pd "10.197.167.110:2379" \
--storage='s3://backup-101/logbackup?access-key=minioadmin&secret-access-key=minioadmin' \
--full-backup-storage='s3://backup-101/snapshot-202606031405?access-key=minioadmin&secret-access-key=minioadmin' \
--restored-ts '2026-06-03 14:07:00+0800' \
--s3.endpoint=http://10.197.167.110:9000 \
--s3.provider=minio
# 输出实例
Starting component br: /root/.tiup/components/br/v8.5.6/br restore point --pd 10.197.167.110:2379 --storage=s3://backup-101/logbackup?access-key=minioadmin&secret-access-key=minioadmin --full-backup-storage=s3://backup-101/snapshot2-202606031405?access-key=minioadmin&secret-access-key=minioadmin --restored-ts 2026-06-03 14:07:00+0800 --s3.endpoint=http://10.197.167.110:9000 --s3.provider=minio
Detail BR log in /tmp/br.log.2026-06-03T14.12.43+0800
Split&Scatter Regions <------------------------------------------------------------------------------------------> 100.00%
Download&Ingest SST <--------------------------------------------------------------------------------------------> 100.00%
Restore Pipeline <-----------------------------------------------------------------------------------------------> 100.00%
[2026/06/03 14:12:49.728 +08:00] [INFO] [collector.go:77] ["Full Restore success summary"] [total-ranges=7] [ranges-succeed=7] [ranges-failed=0] [restore-pipeline=571.853788ms] [merge-ranges=395.463µs] [split-regions=65.06666ms] [restore-files=399.115264ms] [default-CF-files=0] [write-CF-files=7] [split-keys=1] [total-take=6.663964908s] [restore-data-size(after-compressed)=25.15kB] [Size=25150] [BackupTS=466738676870152193] [RestoreTS=466738784087048224] [total-kv=8] [total-kv-size=697B] [average-speed=104.6B/s]
Restore Meta Files <..................................................................................................> ?%
Restore Files(SST + Log) <---------------------------------------------------------------------------------------> 100.00%
[2026/06/03 14:12:54.858 +08:00] [INFO] [collector.go:77] ["restore log success summary"] [total-take=5.129591609s] [source-start-point=466738676870152193] [source-end-point=466738694062080000] [target-end-point=466738785738555399] [source-start="2026-06-03 14:05:54.418 +0800"] [source-end="2026-06-03 14:07:00 +0800"] [target-end="2026-06-03 14:12:49.718 +0800"] [total-kv-count=0] [skipped-kv-count-by-checkpoint=0] [total-size=0B] [skipped-size-by-checkpoint=0B] ["average-speed (log)"=0B/s] [restore-sst-kv-count=0] [restore-sst-kv-size=0] ["restore-sst-physical-size (after compression)"=0] [restore-sst-total-take=0s] ["average-speed (sst)"=NaNB/s]
使用 Dumpling 和 TiDB Lightning 备份与恢复
获取 Dumpling 所需要的上游数据库权限
需要的权限
-
PROCESS:需要该权限用于查询集群信息以获取 PD 地址,从而通过 PD 控制 GC。
-
SELECT:导出目标表时需要。
-
RELOAD:
consistency级别为flush时需要,当上游为 RDS 或采用托管服务时,可忽略该权限。 -
LOCK TABLES:
consistency级别为lock时需要,需要导出的库表都有该权限。 -
REPLICATION CLIENT:导出 metadata 记录数据快照点时需要,可选,如果不需要导出 metadata,可忽略该权限。
-
SHOW VIEW:需要该权限收集用于导出的视图元数据。
GRANT
SELECT,
PROCESS,
RELOAD,
LOCK TABLES,
REPLICATION CLIENT,
SHOW VIEW
ON . TO 'dumper'@'%';-- 刷新权限生效
FLUSH PRIVILEGES;
获取 TiDB Lightning 所需要数据库的下游权限
| 特性 | 作用域 | 所需权限 | 备注 | |
|---|---|---|---|---|
| 必需 | 基本功能 | 目标 table | CREATE, SELECT, INSERT, UPDATE, DELETE, DROP, ALTER | DROP 仅 tidb-lightning-ctl 在执行 checkpoint-destroy-all 时需要 |
| 目标 database | CREATE | |||
| 必需 | 逻辑导入模式 | information_schema.columns | SELECT | |
| 物理导入模式 | mysql.tidb | SELECT | ||
| - | SUPER | |||
| - | RESTRICTED_VARIABLES_ADMIN, RESTRICTED_TABLES_ADMIN | 当目标 TiDB 开启 SEM | ||
| 推荐 | 冲突检测,max-error | lightning.task-info-schema-name 配置的 schema | SELECT, INSERT, UPDATE, DELETE, CREATE, DROP | 如不需要,该值必须设为 "" |
| 可选 | 并行导入 | lightning.meta-schema-name 配置的 schema | SELECT, INSERT, UPDATE, DELETE, CREATE, DROP | 如不需要,该值必须设为 "" |
| 可选 | checkpoint.driver = "mysql" | checkpoint.schema 设置 | SELECT, INSERT, UPDATE, DELETE, CREATE, DROP |
-- 全库基础DDL/DML(导入表创建、删改数据、删表、改表)
GRANT CREATE,SELECT,INSERT,UPDATE,DELETE,DROP,ALTER ON *.* TO 'lightning'@'%';
-- 读取系统库information_schema(逻辑导入必备)
GRANT SELECT ON information_schema.columns TO 'lightning'@'%';
-- 物理导入需要读取mysql.tidb
GRANT SELECT ON mysql.tidb TO 'lightning'@'%';
-- SUPER权限(必配,调整会话参数、开关加速导入)
GRANT SUPER ON *.* TO 'lightning'@'%';
-- SEM安全增强模式才需要下面两个,没开SEM可以不加
-- GRANT RESTRICTED_VARIABLES_ADMIN,RESTRICTED_TABLES_ADMIN ON *.* TO 'lightning'@'%';
使用 Dumpling 备份全量数据
# 运行以下命令,从 TiDB 导出全量数据至 Amazon S3 存储路径 s3://my-bucket/sql-backup
# 自建导出的需要执行
export AWS_ACCESS_KEY_ID=minioadmin
export AWS_SECRET_ACCESS_KEY=minioadmin
tiup dumpling -h 10.197.167.110 -P 4000 -u root -p'X95+y3j6J_27AsU^@u' -t 16 -r 200000 -F 256MiB -B test -f 'test.table[12]' -o 's3://backup-101/sql-backup' \
--s3.endpoint=http://10.197.167.110:9000 \
...
[2026/06/03 14:58:38.064 +08:00] [INFO] [collector.go:264] ["backup success summary"] [total-ranges=1] [ranges-succeed=1] [ranges-failed=0] [total-take=23.340611ms]
[2026/06/03 14:58:38.081 +08:00] [INFO] [tso_dispatcher.go:264] ["[tso] stop fetching the pending tso requests due to context canceled"] [dc-location=global]
[2026/06/03 14:58:38.081 +08:00] [INFO] [tso_dispatcher.go:201] ["[tso] exit tso dispatcher"] [dc-location=global]
[2026/06/03 14:58:38.081 +08:00] [INFO] [main.go:82] ["dump data successfully, dumpling will exit now"]
使用 TiDB Lightning 恢复全量数据
编写配置文件 tidb-lightning.toml,将 Dumpling 备份的全量数据从 s3://my-bucket/sql-backup 恢复到目标 TiDB 集群:
[lightning]
# 日志
level = "info"
file = "tidb-lightning.log"
[tikv-importer]
# "local":默认使用该模式,适用于 TB 级以上大数据量,但导入期间下游 TiDB 无法对外提供服务。
# "tidb":TB 级以下数据量也可以采用`tidb`后端模式,下游 TiDB 可正常提供服务。关于后端模式更多信息请参阅:https://docs.pingcap.com/tidb/stable/tidb-lightning-backends
backend = "local"
# 设置排序的键值对的临时存放地址,目标路径必须是一个空目录,目录空间须大于待导入数据集的大小。建议设为与 `data-source-dir` 不同的磁盘目录并使用闪存介质,独占 IO 会获得更好的导入性能
sorted-kv-dir = "${sorted-kv-dir}"
[mydumper]
# 源数据目录,即上一章节中 Dumpling 保存数据的路径。
data-source-dir = "s3://backup-101/sql-backup" # 本地或 S3 路径,例如:'s3://my-bucket/sql-backup'
[tidb]
# 目标集群的信息
host = 10.197.167.110 # 例如:172.16.32.1
port = 4000 # 例如:4000
user = "root" # 例如:"root"
password = "X95+y3j6J_27AsU^@u" # 例如:"rootroot"
status-port = 10080 # 导入过程 Lightning 需要在从 TiDB 的"状态端口"获取表结构信息,例如:10080
pd-addr = "10.197.167.110:2379" # 集群 PD 的地址,Lightning 通过 PD 获取部分信息,例如 172.16.31.3:2379。当 backend = "local" 时 status-port 和 pd-addr 必须正确填写,否则导入将出现异常。
运行 tidb-lightning。如果直接在命令行中启动程序,可能会因为 SIGHUP 信号而退出,建议配合 nohup 或 screen 等工具
若从 Amazon S3 导入,则需将有权限访问该 S3 后端存储的账号的 SecretKey 和 AccessKey 作为环境变量传入 Lightning 节点。同时还支持从 ~/.aws/credentials 读取凭证文件。
sh
export AWS_ACCESS_KEY_ID=minioadmin
export AWS_SECRET_ACCESS_KEY=minioadmin
nohup tiup tidb-lightning -config tidb-lightning.toml > nohup.out 2>&1 &
导入开始后,可以通过 grep 日志关键字 progress 查看进度,默认 5 分钟更新一次。
导入完毕后,TiDB Lightning 会自动退出。查看 tidb-lightning.log 日志末尾是否有 the whole procedure completed,如果有,数据导入成功,恢复完成
三、数据高可用
支持的集群模式:分布式
最小高可用集群(生产起步标准 |3 台机器)
是否有自带高可用管理工具:是,核心内置高可用组件 PD ,官方配套高可用管理工具 TiUP【https://docs.pingcap.com/zh/tidb/stable/production-deployment-using-tiup/】
拓扑图:
┌───────────────────── Node1(10.0.10.11) ───────────────────┐
│ PD-1(2379) │ TiKV-1(20160) │ TiDB-1(4000) │ Prometheus+Grafana │
└───────────────────────────────────────────────────────────────┘
↓ ↓ ↓
┌───────────────────── Node2(10.0.10.12) ───────────────────┐
│ PD-2(2379) │ TiKV-2(20160) │ TiDB-2(4000) │ │
└───────────────────────────────────────────────────────────────┘
↓ ↓
┌───────────────────── Node3(10.0.10.13) ───────────────────┐
│ PD-3(2379) │ TiKV-3(20160) │ │
└────────────────────────────────────────────────────────────┘
【集群逻辑关联】
1.PD集群:PD1 ↔ PD2 ↔ PD3(Raft选主,元数据调度)
2.TiKV集群:TiKV1/TiKV2/TiKV3 数据3副本跨三节点
3.TiDB接入:TiDB1+TiDB2 前端SQL节点,上层可挂TiProxy/HAProxy做负载均衡
4.监控:Node1部署Prometheus+Grafana统一采集全集群指标
首先每台主机完成 [单机版本安装 6.1 步骤](#单机版本安装 6.1 步骤)
初始化集群拓扑文件(与单机部署不同)
执行如下命令,生成集群初始化配置文件:
tiup cluster template > topology.yaml
# 针对两种常用的部署场景,也可以通过以下命令生成建议的拓扑模板
# 单台机器部署多个实例
tiup cluster template --full > topology.yaml
# 跨机房部署 TiDB 集群
tiup cluster template --multi-dc > topology.yaml
查看配置文件并修改
vim topology.yaml
global:
user: "tidb"
ssh_port: 22
deploy_dir: "/tidb-deploy"
data_dir: "/data/tidbdata"
listen_host: 0.0.0.0
arch: "amd64"
monitored:
node_exporter_port: 9100
blackbox_exporter_port: 9115
server_configs:
# 放宽慢 SQL 阈值、关闭 binlog 精简资源
tidb:
log.slow-threshold: 300
binlog.enable: false
binlog.ignore-error: false
# 普通 KV 读隔离资源,SQL 下推计算共用资源,兼顾联机业务 + 统计查询
tikv:
readpool.storage.use-unified-pool: false
readpool.coprocessor.use-unified-pool: true
# Leader 慢速调度、Region 快速均衡、副本慢速修复,平衡集群均衡速度与业务稳定性
pd:
schedule.leader-schedule-limit: 4
schedule.region-schedule-limit: 2048
schedule.replica-schedule-limit: 64
pd_servers:
- host: 10.0.10.11
- host: 10.0.10.12
- host: 10.0.10.13
tidb_servers:
- host: 10.0.10.11
- host: 10.0.10.12
tikv_servers:
- host: 10.0.10.11
- host: 10.0.10.12
- host: 10.0.10.13
monitoring_servers:
- host: 10.0.10.11
grafana_servers:
- host: 10.0.10.11
alertmanager_servers:
- host: 10.0.10.11
集群搭建
配置 ssh 免密
# 配置免密码,敲三个回车
ssh-keygen -t rsa
# copy
ssh-copy-id 10.197.167.11{1,2,5}
执行部署命令
执行部署命令前,先使用 check 及 check --apply 命令检查和自动修复集群存在的潜在风险:
# 检查潜在风险
tiup cluster check ./topology.yaml --user root
# 自动修复
tiup cluster check ./topology.yaml --apply --user root
部署 TiDB 集群
sh
tiup cluster deploy tidb-test v8.5.6 ./topology.yaml --user root [-p] [-i /home/root/.ssh/gcp_rsa]
tidb-test为部署的集群名称。v8.5.6为部署的集群版本,可以通过执行tiup list tidb来查看 TiUP 支持的最新可用版本。- 初始化配置文件为
topology.yaml。 --user root表示通过 root 用户登录到目标主机完成集群部署,该用户需要有 ssh 到目标机器的权限,并且在目标机器有 sudo 权限。也可以用其他有 ssh 和 sudo 权限的用户完成部署。- -i 及 -p 为可选项,如果已经配置免密登录目标机,则不需填写。否则选择其一即可,-i 为可登录到目标机的 root 用户(或
--user指定的其他用户)的私钥,也可使用 -p 交互式输入该用户的密码。
预期日志结尾输出 Deployed cluster tidb-test successfully 关键词,表示部署成功。
查看 TiUP 管理的集群情况
tiup cluster list
[tidb@nzl-tidb1 ~]$ tiup cluster list
Name User Version Path PrivateKey
---- ---- ------- ---- ----------
tidb-test tidb v8.5.6 /home/tidb/.tiup/storage/cluster/clusters/tidb-test /home/tidb/.tiup/storage/cluster/clusters/tidb-test/ssh/id_rsa
# 检查部署的 TiDB 集群情况
tiup cluster display tidb-test
# 预期输出包括 tidb-test 集群中实例 ID、角色、主机、监听端口和状态(由于还未启动,所以状态为 Down/inactive)、目录信息。
启动集群
# 安全启动(会生成仅此一次出现的密码)
tiup cluster start tidb-test --init
...
+ [ Serial ] - UpdateTopology: cluster=tidb-test
Started cluster `tidb-test` successfully
The root password of TiDB database has been changed.
The new password is: 'CcX3J4@89p+-N0qa_5'.
Copy and record it to somewhere safe, it is only displayed once, and will not be stored.
The generated password can NOT be get and shown again.
# 普通启动
tiup cluster start tidb-test
# 预期结果输出 Started cluster `tidb-test` successfully,表示启动成功。使用普通启动方式后,可通过无密码的 root 用户登录数据库。
使用 tiup cluster display tidb-test 命令验证集群运行状态,预期结果输出:各节点 Status 状态信息为 Up 说明集群状态正常。
[tidb@nzl-tidb1 ~]$ tiup cluster display tidb-test
Cluster type: tidb
Cluster name: tidb-test
Cluster version: v8.5.6
Deploy user: tidb
SSH type: builtin
Dashboard URL: http://10.0.10.13:2379/dashboard
Dashboard URLs: http://10.0.10.13:2379/dashboard
Grafana URL: http://10.0.10.11:3000
ID Role Host Ports OS/Arch Status Data Dir Deploy Dir
-- ---- ---- ----- ------- ------ -------- ----------
10.0.10.11:9093 alertmanager 10.0.10.11 9093/9094 linux/x86_64 Up /data/tidbdata/alertmanager-9093 /tidb-deploy/alertmanager-9093
10.0.10.11:3000 grafana 10.0.10.11 3000 linux/x86_64 Up - /tidb-deploy/grafana-3000
10.0.10.11:2379 pd 10.0.10.11 2379/2380 linux/x86_64 Up /data/tidbdata/pd-2379 /tidb-deploy/pd-2379
10.0.10.12:2379 pd 10.0.10.12 2379/2380 linux/x86_64 Up /data/tidbdata/pd-2379 /tidb-deploy/pd-2379
10.0.10.13:2379 pd 10.0.10.13 2379/2380 linux/x86_64 Up|L|UI /data/tidbdata/pd-2379 /tidb-deploy/pd-2379
10.0.10.11:9090 prometheus 10.0.10.11 9090/9115/9100/12020 linux/x86_64 Up /data/tidbdata/prometheus-9090 /tidb-deploy/prometheus-9090
10.0.10.11:4000 tidb 10.0.10.11 4000/10080 linux/x86_64 Up - /tidb-deploy/tidb-4000
10.0.10.12:4000 tidb 10.0.10.12 4000/10080 linux/x86_64 Up - /tidb-deploy/tidb-4000
10.0.10.11:20160 tikv 10.0.10.11 20160/20180 linux/x86_64 Up /data/tidbdata/tikv-20160 /tidb-deploy/tikv-20160
10.0.10.12:20160 tikv 10.0.10.12 20160/20180 linux/x86_64 Up /data/tidbdata/tikv-20160 /tidb-deploy/tikv-20160
10.0.10.13:20160 tikv 10.0.10.13 20160/20180 linux/x86_64 Up /data/tidbdata/tikv-20160 /tidb-deploy/tikv-20160
Total nodes: 11
Leader 故障转移
在 TiDB 集群中,Leader 故障转移 主要涉及两类:
- PD Leader(集群管理节点)故障转移
- TiKV Region Leader(数据分片 Leader)故障转移
查看 PD Leader
tiup ctl:v8.5.6 pd -u http://10.0.10.11:2379 member
[tidb@nzl-tidb1 ~]$ tiup ctl:v8.5.6 pd -u http://10.0.10.11:2379 member
Starting component ctl: /home/tidb/.tiup/components/ctl/v8.5.6/ctl pd -u http://10.0.10.11:2379 member
...
"leader": {
"name": "pd-10.0.10.13-2379",
"member_id": 10718003975178112822,
"peer_urls": [
"http://10.0.10.13:2380"
],
"client_urls": [
"http://10.0.10.13:2379"
],
"deploy_path": "/tidb-deploy/pd-2379/bin",
"binary_version": "v8.5.6",
"git_hash": "21bd0a379e5f9d2be11a92d17645a6ada19f02c1"
},
...
# 当前PD leader = pd-10.0.10.13-2379
模拟 PD Leader 故障转移
systemctl stop pd-2379
# 查看集群状态PD leader Down|UI
10.0.10.13:2379 pd 10.0.10.13 2379/2380 linux/x86_64 Down|UI /data/tidbdata/pd-2379 /tidb-deploy/pd-2379
再次查看 pd leader 变成 pd-10.0.10.12-2379
tiup ctl:v8.5.6 pd -u http://10.0.10.11:2379 member
...
"leader": {
"name": "pd-10.0.10.12-2379",
"member_id": 15625154777446200056,
"peer_urls": [
"http://10.0.10.12:2380"
],
"client_urls": [
"http://10.0.10.12:2379"
],
"deploy_path": "/tidb-deploy/pd-2379/bin",
"binary_version": "v8.5.6",
"git_hash": "21bd0a379e5f9d2be11a92d17645a6ada19f02c1"
}
...
模拟TiKV Leader故障转移
查看 TiKV Region Leader
mysql -h 10.0.10.11 -P 4000 -u root -p'CcX3J4@89p+-N0qa_5'
SHOW TABLE test.t1 REGIONS;
mysql> SHOW TABLE test.t1 REGIONS;
+-----------+-----------+----------+-----------+-----------------+--------------+------------+---------------+------------+----------------------+------------------+------------------------+------------------+
| REGION_ID | START_KEY | END_KEY | LEADER_ID | LEADER_STORE_ID | PEERS | SCATTERING | WRITTEN_BYTES | READ_BYTES | APPROXIMATE_SIZE(MB) | APPROXIMATE_KEYS | SCHEDULING_CONSTRAINTS | SCHEDULING_STATE |
+-----------+-----------+----------+-----------+-----------------+--------------+------------+---------------+------------+----------------------+------------------+------------------------+------------------+
| 46 | t_112_ | 78000000 | 277 | 5 | 47, 145, 277 | 0 | 0 | 213156 | 2 | 1857 | | |
+-----------+-----------+----------+-----------+-----------------+--------------+------------+---------------+------------+----------------------+------------------+------------------------+------------------+
1 row in set (0.00 sec)
LEADER_STORE_ID = 5
确认 Store 5 是哪台机器
SELECT
STORE_ID,
ADDRESS,
STORE_STATE_NAME
FROM information_schema.tikv_store_status;
+----------+----------------------+------------------+
| STORE_ID | ADDRESS | STORE_STATE_NAME |
+----------+----------------------+------------------+
| 1 | 10.0.10.13:20160 | Up |
| 2 | 10.0.10.12:20160 | Up |
| 5 | 10.0.10.11:20160 | Up |
+----------+----------------------+------------------+
3 rows in set (0.01 sec)
TiKV Region Leader 是 10.0.10.11:20160
停止 store 5 leader
systemctl stop tikv-20160
查看 leader
[tidb@nzl-tidb1 ~]$ tiup ctl:v8.5.6 pd -u http://10.0.10.11:2379 region 46
Starting component ctl: /home/tidb/.tiup/components/ctl/v8.5.6/ctl pd -u http://10.0.10.11:2379 region 46
{"id":46,"start_key":"7480000000000000FF7000000000000000F8","end_key":"7800000000000000FB","epoch":{"conf_ver":5,"version":117},"peers":[{"role_name":"Voter","id":47,"store_id":1},{"role_name":"Voter","id":145,"store_id":2},{"role_name":"Voter","id":277,"store_id":5}],"leader":{"role_name":"Voter","id":145,"store_id":2},"cpu_usage":0,"written_bytes":0,"read_bytes":213156,"written_keys":0,"read_keys":4762,"approximate_size":2,"approximate_keys":1835}
"leader":{"role_name": "Voter", "id": 145, "store_id": 2}
leader 从 store 5→store 2
计划切换
PD leader计划切换
# 查看当前PD leader
tiup ctl:v8.5.6 pd -u http://10.0.10.11:2379 member
...
"leader": {
"name": "pd-10.0.10.12-2379",
...
# 手动转移PD leader
tiup ctl:v8.5.6 pd -u http://10.0.10.12:2379 member leader resign
# 再次查看
tiup ctl:v8.5.6 pd -u http://10.0.10.12:2379 member
...
"leader": {
"name": "pd-10.0.10.13-2379",
"member_id": 10718003975178112822,
"peer_urls": [
"http://10.0.10.13:2380"
],
...
这个步骤是当前 Leader 主动放弃,然后重新选举
异常监控
| 关键监控指标 | 含义 | 采集方式 | 正常值 | 告警阈值 |
|---|---|---|---|---|
| 集群状态(Cluster Status) | 检查所有组件运行状态 | tiup cluster display tidb-cluster |
Up | 任意节点 Down |
| PD Leader 状态 | PD 集群 Leader 是否正常 | Grafana → PD Dashboard | Leader 正常存在 | Leader 丢失超过 30 秒 |
| PD 节点存活数 | PD 服务节点数量 | Prometheus 指标 pd_cluster_status |
与部署数一致 | 节点减少 |
| TiKV 节点存活数 | TiKV 节点运行状态 | Grafana → TiKV Dashboard | 全部 Online | 节点 Offline |
| TiDB 节点存活数 | SQL 服务状态 | Grafana → TiDB Dashboard | 全部 Up | 节点异常退出 |
| Region 健康度 | 数据分片是否正常 | Grafana → PD Dashboard | Healthy | Unhealthy Region > 0 |
| Region 副本状态 | Region 副本数量是否满足配置 | PD Dashboard | 副本数满足 3 副本 | 缺失副本 |
| Leader Balance | Region Leader 分布均衡情况 | PD Dashboard | 基本均衡 | 单节点 Leader 占比 > 50% |
| Store 容量使用率 | TiKV 磁盘使用率 | Node Exporter | < 70% | > 80% |
| 磁盘剩余空间 | TiKV 节点磁盘空间 | Linux df 命令/Grafana | > 20% | < 15% |
| CPU 使用率 | 节点 CPU 负载情况 | Node Exporter | < 70% | > 85% |
| 内存使用率 | 节点内存占用情况 | Node Exporter | < 75% | > 85% |
| 系统负载 Load | Linux 负载情况 | Node Exporter | Load < CPU核心数 | Load > 2×CPU 核心数 |
| 网络延迟 | 节点间通信延迟 | Grafana Network Dashboard | < 5ms | > 50ms |
| 网络丢包率 | 网络质量监控 | Ping/Node Exporter | 0% | > 1% |
| QPS(Query Per Second) | 每秒处理 SQL 数量 | TiDB Dashboard | 根据业务波动 | 突降 50%以上 |
| TPS(Transaction Per Second) | 每秒事务数 | TiDB Dashboard | 稳定 | 异常下降 |
| SQL 响应时间 | SQL 平均执行时间 | TiDB Dashboard | < 100ms | > 500ms |
| 慢 SQL 数量 | 慢查询统计 | information_schema.slow_query |
0~少量 | 持续增长 |
| 活跃连接数 | 当前数据库连接数 | SQL 查询 | 正常范围 | > 最大连接数 80% |
| 事务冲突数 | 分布式事务冲突情况 | TiDB Dashboard | 接近 0 | 持续增长 |
| Commit 耗时 | 事务提交延迟 | TiDB Dashboard | < 50ms | > 200ms |
| GC 运行状态 | 垃圾回收是否正常 | SQL 查询 GC 变量 | 正常运行 | GC 失败 |
| RocksDB 写入延迟 | TiKV 底层存储性能 | TiKV Dashboard | < 20ms | > 100ms |
| RocksDB Compaction 状态 | SST 文件压缩情况 | TiKV Dashboard | 正常 | Pending 持续增长 |
| Raft 日志同步延迟 | 副本同步情况 | TiKV Dashboard | < 100ms | > 1s |
| Raft 消息丢失率 | Raft 通信状态 | TiKV Dashboard | 0 | 持续增长 |
| Store Down 时间 | 节点离线时长 | PD Dashboard | 0 | > 5 分钟 |
| 数据副本同步状态 | 数据一致性情况 | PD Dashboard | 正常 | 副本异常 |
推荐使用CLup平台,详情请看官网:https://www.csudata.com/clup/manual