本文档风哥主要介绍TiDB性能基线建立相关知识,包括性能基线基础、TiDB性能特性、基线建立原理、基线规划、指标规划、性能建议、基线建立实施方案、指标采集实施方案、基线监控实施方案等内容,风哥教程参考TiDB官方文档性能优化章节,适合DBA人员在学习和测试中使用,如果要应用于生产环境则需要自行确认。
Part01-基础概念与理论知识
1.1 性能基线基础
性能基线的核心概念:
- 性能基线:系统在正常运行状态下的性能指标基准,用于评估系统性能变化。
- 基线指标:构成性能基线的具体指标,如QPS、响应时间、CPU使用率等。
- 基线建立:通过采集和分析系统在正常运行状态下的性能数据,建立性能基线。
- 基线监控:实时监控系统性能指标,与性能基线进行比较,发现性能异常。
- 基线调整:根据系统变化和业务需求,调整性能基线。
- 评估系统性能变化
- 发现性能异常
- 优化系统配置
- 预测系统容量需求
- 评估系统改进效果
1.2 TiDB性能特性
TiDB的性能特性:
## 1. 核心性能指标
– QPS:每秒查询数
– 响应时间:SQL执行时间
– 并发连接数:同时连接的客户端数量
– 吞吐量:系统处理数据的能力
– 资源使用率:CPU、内存、磁盘、网络等资源的使用情况
## 2. 性能瓶颈
– SQL执行:慢查询、复杂查询
– 存储层:I/O性能、Raft复制
– 调度层:PD调度、TiKV分片
– 网络:网络延迟、带宽限制
– 硬件:CPU、内存、磁盘性能
## 3. 性能优化策略
– SQL优化:优化查询语句、创建索引
– 存储优化:调整TiKV参数、使用SSD
– 调度优化:调整PD调度策略
– 网络优化:优化网络配置、减少网络延迟
– 硬件优化:升级硬件配置
## 4. 性能监控
– Prometheus:采集和存储性能指标
– Grafana:展示性能指标
– Alertmanager:告警管理
– 系统监控:监控主机性能
– 应用监控:监控应用性能
## 5. 性能测试
– 基准测试:使用Sysbench、TiKV-Ctl等工具进行基准测试
– 压力测试:模拟高负载场景
– 回归测试:验证性能改进效果
– 容量测试:测试系统容量极限
– 稳定性测试:测试系统长期运行稳定性
1.3 基线建立原理
性能基线建立的原理:
## 1. 数据采集
– 采集时间:选择系统正常运行的时间段
– 采集频率:根据指标重要性设置不同的采集频率
– 采集范围:覆盖所有关键指标
– 采集工具:使用Prometheus、Node Exporter等工具
– 数据存储:存储足够的历史数据
## 2. 数据分析
– 统计分析:计算指标的平均值、最大值、最小值、标准差等
– 趋势分析:分析指标的变化趋势
– 异常检测:识别异常数据
– 相关性分析:分析不同指标之间的相关性
– 阈值确定:根据分析结果确定合理的阈值
## 3. 基线确定
– 静态基线:基于历史数据确定固定的基线值
– 动态基线:根据系统状态自动调整基线值
– 季节性基线:考虑业务的季节性变化
– 多维度基线:从不同维度建立基线
– 分层基线:建立不同层次的基线
## 4. 基线验证
– 测试验证:通过测试验证基线的合理性
– 实际验证:在实际运行中验证基线的有效性
– 调整优化:根据验证结果调整基线
– 持续更新:定期更新基线
## 5. 基线应用
– 性能监控:与基线比较,发现性能异常
– 性能优化:基于基线进行性能优化
– 容量规划:基于基线预测容量需求
– 故障排查:基于基线分析故障原因
– 性能评估:评估系统性能改进效果
Part02-生产环境规划与建议
2.1 基线规划
基线规划:
## 1. 基线目标
– 全面覆盖:覆盖所有关键性能指标
– 准确可靠:基线数据准确可靠
– 动态调整:根据系统变化调整基线
– 易于理解:基线易于理解和使用
– 可操作性:基线具有可操作性
## 2. 基线类型
– 系统基线:系统级别的性能基线
– 组件基线:各组件的性能基线学习交流加群风哥QQ113257174
– 业务基线:业务级别的性能基线
– 时间基线:不同时间段的性能基线
– 场景基线:不同场景的性能基线
## 3. 基线指标
– 核心指标:QPS、响应时间、资源使用率等
– 次要指标:连接数、缓存命中率等
– 业务指标:业务吞吐量、业务响应时间等
– 系统指标:CPU、内存、磁盘、网络等
– 组件指标:TiDB、TiKV、PD等组件的指标
## 4. 基线采集
– 采集时间:选择系统正常运行的时间段
– 采集频率:根据指标重要性设置不同的采集频率
– 采集工具:使用Prometheus、Node Exporter等工具
– 数据存储:存储足够的历史数据
– 数据质量:确保数据的准确性和完整性
## 5. 基线管理
– 基线版本:管理基线的版本
– 基线更新:定期更新基线
– 基线对比:对比不同版本的基线
– 基线文档:记录基线的相关信息
– 基线审计:审计基线的使用情况
2.2 指标规划
指标规划:
## 1. 指标分类
– 系统指标:CPU、内存、磁盘、网络等
– 数据库指标:QPS、响应时间、连接数等
– 存储指标:I/O性能、磁盘使用率等
– 网络指标:网络延迟、带宽使用率等
– 业务指标:业务吞吐量、业务响应时间等
## 2. 指标选择
– 相关性:选择与系统性能相关的指标
– 可测量性:选择可准确测量的指标
– 敏感性:选择对性能变化敏感的指标
– 可操作性:选择可通过优化手段改善的指标
– 代表性:选择能够代表系统整体性能的指标
## 3. 指标采集
– 采集工具:选择合适的采集工具
– 采集频率:根据指标重要性设置不同的采集频率
– 采集范围:覆盖所有关键指标
– 数据存储:选择合适的存储方式
– 数据处理:对采集的数据进行处理和分析
## 4. 指标分析
– 统计分析:计算指标的统计值
– 趋势分析:分析指标的变化趋势
– 异常检测:识别异常数据
– 相关性分析:分析不同指标之间的相关性
– 预测分析:预测指标的未来变化
## 5. 指标展示
– 仪表盘:使用Grafana等工具展示指标
– 报表:生成定期性能报表
– 告警:设置指标告警阈值
– 可视化:使用图表等方式可视化指标
– 导出:支持指标数据导出
2.3 性能建议
性能建议:
## 1. 硬件建议
– CPU:选择多核CPU,提高处理能力
– 内存:增加内存容量,提高缓存能力
– 存储:使用SSD存储,提高I/O性能
– 网络:使用高速网络,减少网络延迟
– 服务器:选择性能稳定的服务器
## 2. 系统配置建议
– 操作系统:选择稳定的操作系统版本
– 内核参数:优化内核参数,如文件描述符、网络参数等
– 文件系统:选择适合的文件系统,如ext4、xfs等
– 磁盘调度:选择适合的磁盘调度算法
– 内存管理:优化内存管理,如关闭透明大页
## 3. 数据库配置建议
– TiDB参数:优化TiDB参数,如tidb_max_txn_size、tidb_mem_quota_query等
– TiKV参数:优化TiKV参数,如raftstore.apply-pool-size、rocksdb.max-open-files等
– PD参数:优化PD参数,如replication.location-labels、scheduler.max-merge-region-size等
– 连接池:配置合理的连接池大小
– 缓存:配置合理的缓存大小
## 4. 应用优化建议
– SQL优化:优化查询语句,避免全表扫描
– 索引设计:合理设计索引,提高查询性能
– 事务管理:优化事务大小和隔离级别
– 连接管理:合理管理数据库连接
– 批处理:使用批处理减少网络往返
## 5. 监控建议
– 监控工具:使用Prometheus、Grafana等工具
– 监控指标:监控关键性能指标
– 告警设置:设置合理的告警阈值
– 监控频率:根据指标重要性设置不同的监控频率
– 监控分析:定期分析监控数据,发现性能问题
Part03-生产环境项目实施方案
3.1 基线建立实施方案
3.1.1 基线数据采集
## 1. 配置Prometheus
$ cat > prometheus.yml << EOF
global:
scrape_interval: 15s
evaluation_interval: 15s
alerting:
alertmanagers:
- static_configs:
- targets: ['localhost:9093']
rule_files:
- "rules/*.yml"
scrape_configs:
- job_name: 'tidb'
static_configs:
- targets: ['192.168.1.100:9090']
- job_name: 'tikv'
static_configs:
- targets: ['192.168.1.101:9091', '192.168.1.102:9091', '192.168.1.103:9091']
- job_name: 'pd'
static_configs:
- targets: ['192.168.1.100:9092']
- job_name: 'node'
static_configs:
- targets: ['192.168.1.100:9100', '192.168.1.101:9100', '192.168.1.102:9100', '192.168.1.103:9100']
EOF
## 2. 启动Prometheus
$ prometheus --config.file=prometheus.yml --storage.tsdb.path=/tidb/prometheus/data --storage.tsdb.retention.time=30d
## 3. 采集基线数据
# 选择系统正常运行的时间段(如业务低峰期)
# 持续采集7天的数据
## 4. 导出基线数据
$ curl -X GET "http://localhost:9090/api/v1/query_range?query=sum(rate(tidb_server_qps{job='tidb'}[5m]))&start=1609459200&end=1610064000&step=300" > qps_data.json
$ curl -X GET “http://localhost:9090/api/v1/query_range?query=sum(rate(tidb_server_slow_query_count{job=’tidb’}[5m]))&start=1609459200&end=1610064000&step=300” > slow_query_data.json
$ curl -X GET “http://localhost:9090/api/v1/query_range?query=sum(tidb_server_connections{job=’tidb’})&start=1609459200&end=1610064000&step=300” > connections_data.json
3.1.2 基线数据分析
## 1. 分析QPS数据
$ cat > analyze_qps.py << EOF
#!/usr/bin/env python3
# analyze_qps.py
# from:www.itpux.com.qq113257174.wx:itpux-com
# web: http://www.fgedu.net.cn
import json
import numpy as np
# 读取数据
with open('qps_data.json', 'r') as f:
data = json.load(f)
# 提取值
values = []
for result in data['data']['result']:
for value in result['values']:
values.append(float(value[1]))
# 计算统计值
mean = np.mean(values)
std = np.std(values)
max_value = np.max(values)
min_value = np.min(values)
percentile_95 = np.percentile(values, 95)
percentile_99 = np.percentile(values, 99)
# 输出结果
print(f"QPS 平均值: {mean:.2f}")
print(f"QPS 标准差: {std:.2f}")
print(f"QPS 最大值: {max_value:.2f}")
print(f"QPS 最小值: {min_value:.2f}")
print(f"QPS 95分位数: {percentile_95:.2f}")
print(f"QPS 99分位数: {percentile_99:.2f}")
EOF
$ python3 analyze_qps.py
## 2. 分析慢查询数据
$ cat > analyze_slow_query.py << EOF
#!/usr/bin/env python3
import json
import numpy as np
# 读取数据
with open('slow_query_data.json', 'r') as f:
data = json.load(f)
# 提取值
values = []
for result in data['data']['result']:
for value in result['values']:
values.append(float(value[1]))
# 计算统计值
mean = np.mean(values)
std = np.std(values)
max_value = np.max(values)
min_value = np.min(values)
percentile_95 = np.percentile(values, 95)
percentile_99 = np.percentile(values, 99)
# 输出结果
print(f"慢查询数 平均值: {mean:.2f}")
print(f"慢查询数 标准差: {std:.2f}")
print(f"慢查询数 最大值: {max_value:.2f}")
print(f"慢查询数 最小值: {min_value:.2f}")
print(f"慢查询数 95分位数: {percentile_95:.2f}")
print(f"慢查询数 99分位数: {percentile_99:.2f}")
EOF
$ python3 analyze_slow_query.py
## 3. 分析连接数数据
$ cat > analyze_connections.py << EOF
#!/usr/bin/env python3
import json
import numpy as np
# 读取数据
with open('connections_data.json', 'r') as f:
data = json.load(f)
# 提取值
values = []
for result in data['data']['result']:
for value in result['values']:
values.append(float(value[1]))
# 计算统计值
mean = np.mean(values)
std = np.std(values)
max_value = np.max(values)
min_value = np.min(values)
percentile_95 = np.percentile(values, 95)
percentile_99 = np.percentile(values, 99)
# 输出结果
print(f"连接数 平均值: {mean:.2f}")
print(f"连接数 标准差: {std:.2f}")
print(f"连接数 最大值: {max_value:.2f}")
print(f"连接数 最小值: {min_value:.2f}")
print(f"连接数 95分位数: {percentile_95:.2f}")
print(f"连接数 99分位数: {percentile_99:.2f}")
EOF
$ python3 analyze_connections.py
3.2 指标采集实施方案
3.2.1 系统指标采集
## 1. 安装Node Exporter
$ wget https://github.com/prometheus/node_exporter/releases/download/v1.3.1/node_exporter-1.3.1.linux-amd64.tar.gz
$ tar -xzf node_exporter-1.3.1.linux-amd64.tar.gz
$ cd node_exporter-1.3.1.linux-amd64
$ cp node_exporter /tidb/app/node_exporter
## 2. 配置Node Exporter
$ cat > /etc/systemd/system/node_exporter.service << EOF
[Unit]
Description=Node Exporter
After=network.target
[Service]
Type=simple
ExecStart=/tidb/app/node_exporter
[Install]
WantedBy=multi-user.target
EOF
## 3. 启动Node Exporter
$ systemctl daemon-reload
$ systemctl start node_exporter
$ systemctl enable node_exporter
## 4. 验证Node Exporter
$ curl http://localhost:9100/metrics
## 5. 配置Prometheus采集Node Exporter
$ cat >> prometheus.yml << EOF
- job_name: 'node'
static_configs:
- targets: ['192.168.1.100:9100', '192.168.1.101:9100', '192.168.1.102:9100', '192.168.1.103:9100']
EOF
## 6. 重启Prometheus
$ systemctl restart prometheus
3.2.2 数据库指标采集
## 1. 配置TiDB监控
$ cat > tidb.toml << EOF
[metrics]
enable = true
addr = "0.0.0.0:9090"
EOF
## 2. 配置TiKV监控
$ cat > tikv.toml << EOF
[metrics]
enable = true
addr = "0.0.0.0:9091"
EOF
## 3. 配置PD监控
$ cat > pd.toml << EOF
[metrics]
enable = true
addr = "0.0.0.0:9092"
EOF
## 4. 重启集群
$ tiup cluster restart fgedu-tidb-cluster
## 5. 验证监控端点
$ curl http://192.168.1.100:9090/metrics
$ curl http://192.168.1.101:9091/metrics
$ curl http://192.168.1.100:9092/metrics
## 6. 配置Prometheus采集数据库指标
$ cat > prometheus.yml << EOF
global:
scrape_interval: 15s
evaluation_interval: 15s
alerting:
alertmanagers:
- static_configs:
- targets: ['localhost:9093']
rule_files:
- "rules/*.yml"
scrape_configs:
- job_name: 'tidb'
static_configs:
- targets: ['192.168.1.100:9090']
- job_name: 'tikv'
static_configs:
- targets: ['192.168.1.101:9091', '192.168.1.102:9091', '192.168.1.103:9091']
- job_name: 'pd'
static_configs:
- targets: ['192.168.1.100:9092']
EOF
## 7. 重启Prometheus
$ systemctl restart prometheus
3.3 基线监控实施方案
3.3.1 基线监控配置
## 1. 创建基线监控规则
$ cat > /tidb/prometheus/rules/baseline.rules.yml << EOF
groups:
- name: baseline_alerts
rules:
- alert: QPSAboveBaseline
expr: sum(rate(tidb_server_qps{job="tidb"}[5m])) > 12000
for: 5m
labels:
severity: warning
annotations:
summary: “QPS 超过基线”
description: “当前 QPS ({{ $value }}) 超过基线值 (10000)”
– alert: SlowQueryAboveBaseline
expr: sum(rate(tidb_server_slow_query_count{job=”tidb”}[5m])) > 15
for: 5m
labels:
severity: warning
annotations:
summary: “慢查询数超过基线”
description: “当前慢查询数 ({{ $value }}) 超过基线值 (10)”
– alert: ConnectionsAboveBaseline
expr: sum(tidb_server_connections{job=”tidb”}) > 6000
for: 5m
labels:
severity: warning
annotations:
summary: “连接数超过基线”
description: “当前连接数 ({{ $value }}) 超过基线值 (5000)”
EOF
## 2. 配置Alertmanager
$ cat > alertmanager.yml << EOF
global:
resolve_timeout: 5m
smtp_smarthost: 'smtp.example.com:587'
smtp_from: 'admin@example.com'
smtp_auth_username: 'admin@example.com'
smtp_auth_password: 'password'
route:
group_by: ['alertname', 'cluster', 'service']
group_wait: 30s
group_interval: 5m
repeat_interval: 1h
receiver: 'email'
receivers:
- name: 'email'
email_configs:
- to: 'admin@example.com'
send_resolved: true
inhibit_rules:
- source_match:
severity: 'critical'
target_match:
severity: 'warning'
equal: ['alertname', 'cluster', 'service']
EOF
## 3. 启动Alertmanager
$ alertmanager --config.file=alertmanager.yml --storage.path=/tidb/alertmanager/data
## 4. 配置Grafana面板
# 访问 http://localhost:3000
# 点击 "+" → "Dashboard"
# 点击 "Add new panel"
# 面板标题:QPS vs 基线
# 数据源:Prometheus
# 查询语句1:sum(rate(tidb_server_qps{job="tidb"}[5m]))
# 查询语句2:10000 (基线值)
# 图表类型:Graph
# 点击 "Apply"
## 5. 保存Dashboard
# 点击 "Save Dashboard"
# 输入Dashboard名称:TiDB性能基线监控
# 点击 "Save"
3.3.2 基线调整
## 1. 定期分析基线数据
$ cat > analyze_baseline.py << EOF
#!/usr/bin/env python3
# analyze_baseline.py
# from:www.itpux.com.qq113257174.wx:itpux-com
# web: http://www.fgedu.net.cn
import json
import numpy as np
import requests
# 采集最新数据
start_time = "1610064000"
end_time = "1610668800"
step = "300"
# 采集QPS数据
response = requests.get(
f"http://localhost:9090/api/v1/query_range?query=sum(rate(tidb_server_qps{{job='tidb'}}[5m]))&start={start_time}&end={end_time}&step={step}"
)
data = response.json()
# 提取值
values = []
for result in data['data']['result']:
for value in result['values']:
values.append(float(value[1]))
# 计算统计值
mean = np.mean(values)
std = np.std(values)
max_value = np.max(values)
min_value = np.min(values)
percentile_95 = np.percentile(values, 95)
percentile_99 = np.percentile(values, 99)
# 输出结果
print("=== 最新QPS数据 ===")
print(f"平均值: {mean:.2f}")
print(f"标准差: {std:.2f}")
print(f"最大值: {max_value:.2f}")
print(f"最小值: {min_value:.2f}")
print(f"95分位数: {percentile_95:.2f}")
print(f"99分位数: {percentile_99:.2f}")
# 与基线比较
baseline = 10000
if mean > baseline * 1.1:
print(“\n警告: QPS平均值超过基线10%”)
elif mean < baseline * 0.9:
print("\n信息: QPS平均值低于基线10%")
else:
print("\n正常: QPS平均值在基线范围内")
EOF
$ python3 analyze_baseline.py
## 2. 调整基线值
# 根据分析结果调整基线值
$ cat > update_baseline.py << EOF
#!/usr/bin/env python3
import json
# 读取当前规则
with open('/tidb/prometheus/rules/baseline.rules.yml', 'r') as f:
rules = yaml.safe_load(f)
# 更新QPS基线
for rule in rules['groups'][0]['rules']:
if rule['alert'] == 'QPSAboveBaseline':
# 更新为新的基线值
new_baseline = 12000
rule['expr'] = f"sum(rate(tidb_server_qps{{job=\"tidb\"}}[5m])) > {new_baseline}”
rule[‘annotations’][‘description’] = f”当前 QPS ({{ $value }}) 超过基线值 ({new_baseline})”
# 保存更新后的规则
with open(‘/tidb/prometheus/rules/baseline.rules.yml’, ‘w’) as f:
yaml.dump(rules, f)
print(“基线已更新”)
EOF
$ python3 update_baseline.py
## 3. 重启Prometheus
$ systemctl restart prometheus
Part04-生产案例与实战讲解
4.1 基线建立案例
基线建立案例:
## 案例1:TiDB集群性能基线建立
### 步骤1:采集基线数据
# 选择系统正常运行的时间段(如业务低峰期)
# 持续采集7天的数据
### 步骤2:分析数据
$ python3 analyze_qps.py
QPS 平均值: 8500.45
QPS 标准差: 1200.32
QPS 最大值: 12000.78
QPS 最小值: 5000.12
QPS 95分位数: 10500.67
QPS 99分位数: 11500.89
$ python3 analyze_slow_query.py
慢查询数 平均值: 8.56
慢查询数 标准差: 2.34
慢查询数 最大值: 15.23
慢查询数 最小值: 2.11
慢查询数 95分位数: 12.34
慢查询数 99分位数: 14.56
$ python3 analyze_connections.py
连接数 平均值: 4200.78
连接数 标准差: 800.45
连接数 最大值: 5500.90
连接数 最小值: 2800.34
连接数 95分位数: 5000.67
连接数 99分位数: 5300.89
### 步骤3:确定基线值
– QPS基线:10000(95分位数)
– 慢查询数基线:12(95分位数)
– 连接数基线:5000(95分位数)
### 步骤4:配置基线监控
$ cat > /tidb/prometheus/rules/baseline.rules.yml << EOF
groups:
- name: baseline_alerts
rules:
- alert: QPSAboveBaseline
expr: sum(rate(tidb_server_qps{job="tidb"}[5m])) > 10000
for: 5m
labels:
severity: warning
annotations:
summary: “QPS 超过基线”
description: “当前 QPS ({{ $value }}) 超过基线值 (10000)”
– alert: SlowQueryAboveBaseline
expr: sum(rate(tidb_server_slow_query_count{job=”tidb”}[5m])) > 12
for: 5m
labels:
severity: warning
annotations:
summary: “慢查询数超过基线”
description: “当前慢查询数 ({{ $value }}) 超过基线值 (12)”
– alert: ConnectionsAboveBaseline
expr: sum(tidb_server_connections{job=”tidb”}) > 5000
for: 5m
labels:
severity: warning
annotations:
summary: “连接数超过基线”
description: “当前连接数 ({{ $value }}) 超过基线值 (5000)”
EOF
### 步骤5:验证基线
# 观察系统运行情况,验证基线的合理性
# 根据实际情况调整基线值
## 案例2:业务性能基线建立
### 步骤1:定义业务指标
– 业务QPS:每秒业务请求数
– 业务响应时间:业务请求的响应时间
– 业务错误率:业务请求的错误率
### 步骤2:采集业务数据
$ cat > collect_business_metrics.py << EOF
#!/usr/bin/env python3
# collect_business_metrics.py
# from:www.itpux.com.qq113257174.wx:itpux-com
# web: http://www.fgedu.net.cn
import time
import random
import requests
# 模拟业务请求
def simulate_business_requests():
while True:
# 模拟QPS
qps = random.randint(5000, 15000)
# 模拟响应时间
response_time = random.uniform(0.1, 0.5)
# 模拟错误率
error_rate = random.uniform(0, 0.05)
# 发送到Prometheus
payload = {
"business_qps": qps,
"business_response_time": response_time,
"business_error_rate": error_rate
}
try:
requests.post("http://localhost:9091/metrics", data=payload)
except Exception as e:
print(f"Error: {e}")
time.sleep(15)
if __name__ == "__main__":
simulate_business_requests()
EOF
$ nohup python3 collect_business_metrics.py &
### 步骤3:分析业务数据
# 分析业务数据,确定业务性能基线
### 步骤4:配置业务基线监控
# 创建业务基线监控规则
# 配置业务基线监控Dashboard
4.2 指标采集案例
指标采集案例:
## 案例1:全栈指标采集
### 步骤1:安装采集工具
# 安装Node Exporter
$ wget https://github.com/prometheus/node_exporter/releases/download/v1.3.1/node_exporter-1.3.1.linux-amd64.tar.gz
$ tar -xzf node_exporter-1.3.1.linux-amd64.tar.gz
$ cp node_exporter-1.3.1.linux-amd64/node_exporter /tidb/app/node_exporter
# 安装Blackbox Exporter
$ wget https://github.com/prometheus/blackbox_exporter/releases/download/v0.19.0/blackbox_exporter-0.19.0.linux-amd64.tar.gz
$ tar -xzf blackbox_exporter-0.19.0.linux-amd64.tar.gz
$ cp blackbox_exporter-0.19.0.linux-amd64/blackbox_exporter /tidb/app/blackbox_exporter
### 步骤2:配置采集工具
# 配置Node Exporter
$ cat > /etc/systemd/system/node_exporter.service << EOF
[Unit]
Description=Node Exporter
After=network.target
[Service]
Type=simple
ExecStart=/tidb/app/node_exporter
[Install]
WantedBy=multi-user.target
EOF
# 配置Blackbox Exporter
$ cat > blackbox.yml << EOF
modules:
http_2xx:
prober: http
http:
valid_status_codes: [200]
method: GET
tcp_connect:
prober: tcp
icmp:
prober: icmp
EOF
$ cat > /etc/systemd/system/blackbox_exporter.service << EOF
[Unit]
Description=Blackbox Exporter
After=network.target
[Service]
Type=simple
ExecStart=/tidb/app/blackbox_exporter --config.file=/tidb/app/blackbox.yml
[Install]
WantedBy=multi-user.target
EOF
### 步骤3:启动采集工具
$ systemctl daemon-reload
$ systemctl start node_exporter blackbox_exporter
$ systemctl enable node_exporter blackbox_exporter
### 步骤4:配置Prometheus采集
$ cat > prometheus.yml << EOF
global:
scrape_interval: 15s
evaluation_interval: 15s
alerting:
alertmanagers:
- static_configs:
- targets: ['localhost:9093']
rule_files:
- "rules/*.yml"
scrape_configs:
# 系统指标
- job_name: 'node'
static_configs:
- targets: ['192.168.1.100:9100', '192.168.1.101:9100', '192.168.1.102:9100', '192.168.1.103:9100']
# 数据库指标
- job_name: 'tidb'
static_configs:
- targets: ['192.168.1.100:9090']
- job_name: 'tikv'
static_configs:
- targets: ['192.168.1.101:9091', '192.168.1.102:9091', '192.168.1.103:9091']
- job_name: 'pd'
static_configs:
- targets: ['192.168.1.100:9092']
# 网络探测
- job_name: 'blackbox'
metrics_path: /probe
params:
module: [http_2xx]
static_configs:
- targets:
- http://192.168.1.100:4000
- http://192.168.1.100:3000
relabel_configs:
- source_labels: [__address__]
target_label: __param_target
- source_labels: [__param_target]
target_label: instance
- target_label: __address__
replacement: 127.0.0.1:9115
EOF
### 步骤5:重启Prometheus
$ systemctl restart prometheus
## 案例2:自定义指标采集
### 步骤1:创建自定义指标采集脚本
$ cat > custom_metrics.sh << EOF
#!/bin/bash
# custom_metrics.sh
# from:www.itpux.com.qq113257174.wx:itpux-com
# web: http://www.fgedu.net.cn
# 采集业务指标
QPS=$(mysql -h 192.168.1.100 -P 4000 -u root -p password -e "SHOW GLOBAL STATUS LIKE 'Queries';" | grep Queries | awk '{print $2}')
SLOW_QUERIES=$(mysql -h 192.168.1.100 -P 4000 -u root -p password -e "SHOW GLOBAL STATUS LIKE 'Slow_queries';" | grep Slow_queries | awk '{print $2}')
CONNECTIONS=$(mysql -h 192.168.1.100 -P 4000 -u root -p password -e "SHOW GLOBAL STATUS LIKE 'Threads_connected';" | grep Threads_connected | awk '{print $2}')
# 输出指标
echo "# HELP tidb_business_qps Total QPS"
echo "# TYPE tidb_business_qps counter"
echo "tidb_business_qps $QPS"
echo "# HELP tidb_business_slow_queries Total slow queries"
echo "# TYPE tidb_business_slow_queries counter"
echo "tidb_business_slow_queries $SLOW_QUERIES"
echo "# HELP tidb_business_connections Current connections"
echo "# TYPE tidb_business_connections gauge"
echo "tidb_business_connections $CONNECTIONS"
EOF
### 步骤2:配置Prometheus采集自定义指标
$ cat > prometheus.yml << EOF
global:
scrape_interval: 15s
evaluation_interval: 15s
alerting:
alertmanagers:
- static_configs:
- targets: ['localhost:9093']
rule_files:
- "rules/*.yml"
scrape_configs:
# 自定义指标
- job_name: 'custom'
static_configs:
- targets: ['localhost:9101']
metrics_path: '/metrics'
EOF
### 步骤3:启动自定义指标服务
$ nohup bash -c 'while true; do ./custom_metrics.sh > /tidb/custom/metrics.prom; sleep 15; done’ &
$ python3 -m http.server 9101 –directory /tidb/custom
### 步骤4:验证自定义指标
$ curl http://localhost:9101/metrics
4.3 基线监控案例
基线监控案例:
## 案例1:实时基线监控
### 步骤1:创建基线监控Dashboard
# 访问 http://localhost:3000
# 点击 “+” → “Dashboard”
# 点击 “Add new panel”
### 步骤2:配置QPS面板
# 面板标题:QPS vs 基线
# 数据源:Prometheus
# 查询语句1:sum(rate(tidb_server_qps{job=”tidb”}[5m]))
# 查询语句2:10000 (基线值)
# 图表类型:Graph
# 轴标签:QPS
# 单位:ops
# 点击 “Apply”
### 步骤3:配置慢查询面板
# 点击 “Add new panel”
# 面板标题:慢查询数 vs 基线
# 数据源:Prometheus
# 查询语句1:sum(rate(tidb_server_slow_query_count{job=”tidb”}[5m]))
# 查询语句2:12 (基线值)
# 图表类型:Graph
# 轴标签:慢查询数
# 单位:count
# 点击 “Apply”
### 步骤4:配置连接数面板
# 点击 “Add new panel”
# 面板标题:连接数 vs 基线
# 数据源:Prometheus
# 查询语句1:sum(tidb_server_connections{job=”tidb”})
# 查询语句2:5000 (基线值)
# 图表类型:Graph
# 轴标签:连接数
# 单位:count
# 点击 “Apply”
### 步骤5:保存Dashboard
# 点击 “Save Dashboard”
# 输入Dashboard名称:TiDB性能基线监控
# 点击 “Save”
## 案例2:基线告警
### 步骤1:配置基线告警规则
$ cat > /tidb/prometheus/rules/baseline.rules.yml << EOF
groups:
- name: baseline_alerts
rules:
- alert: QPSAboveBaseline
expr: sum(rate(tidb_server_qps{job="tidb"}[5m])) > 10000
for: 5m
labels:
severity: warning
annotations:
summary: “QPS 超过基线”
description: “当前 QPS ({{ $value }}) 超过基线值 (10000)”
– alert: QPSCritical
expr: sum(rate(tidb_server_qps{job=”tidb”}[5m])) > 12000
for: 5m
labels:
severity: critical
annotations:
summary: “QPS 严重超过基线”
description: “当前 QPS ({{ $value }}) 严重超过基线值 (10000)”
– alert: SlowQueryAboveBaseline
expr: sum(rate(tidb_server_slow_query_count{job=”tidb”}[5m])) > 12
for: 5m
labels:
severity: warning
annotations:
summary: “慢查询数超过基线”
description: “当前慢查询数 ({{ $value }}) 超过基线值 (12)”
– alert: ConnectionsAboveBaseline
expr: sum(tidb_server_connections{job=”tidb”}) > 5000
for: 5m
labels:
severity: warning
annotations:
summary: “连接数超过基线”
description: “当前连接数 ({{ $value }}) 超过基线值 (5000)”
EOF
### 步骤2:配置Alertmanager
$ cat > alertmanager.yml << EOF
global:
resolve_timeout: 5m
smtp_smarthost: 'smtp.example.com:587'
smtp_from: 'admin@example.com'
smtp_auth_username: 'admin@example.com'
smtp_auth_password: 'password'
route:
group_by: ['alertname', 'cluster', 'service']
group_wait: 30s
group_interval: 5m
repeat_interval: 1h
receiver: 'email'
routes:
- match:
severity: critical
receiver: 'email'
continue: true
- match:
severity: warning
receiver: 'email'
receivers:
- name: 'email'
email_configs:
- to: 'admin@example.com'
send_resolved: true
inhibit_rules:
- source_match:
severity: 'critical'
target_match:
severity: 'warning'
equal: ['alertname', 'cluster', 'service']
EOF
### 步骤3:启动Alertmanager
$ alertmanager --config.file=alertmanager.yml --storage.path=/tidb/alertmanager/data
### 步骤4:验证告警
# 模拟高QPS场景
$ mysql -h 192.168.1.100 -P 4000 -u root -p password -e "CREATE DATABASE IF NOT EXISTS fgedudb;"
$ mysql -h 192.168.1.100 -P 4000 -u root -p password -e "CREATE TABLE IF NOT EXISTS fgedudb.fgedu_users (id INT PRIMARY KEY, name VARCHAR(255));"
$ mysql -h 192.168.1.100 -P 4000 -u root -p password -e "INSERT INTO fgedudb.fgedu_users VALUES (1, 'user1'), (2, 'user2'), (3, 'user3');"
# 模拟高并发查询
$ cat > stress_test.sh << EOF
#!/bin/bash
# stress_test.sh
# from:www.itpux.com.qq113257174.wx:itpux-com
# web: http://www.fgedu.net.cn
for i in {1..10000}
do
mysql -h 192.168.1.100 -P 4000 -u root -p password -e "SELECT * FROM fgedudb.fgedu_users;"
sleep 0.01
done
EOF
$ chmod +x stress_test.sh
$ nohup ./stress_test.sh &
# 查看告警
# 访问 http://localhost:9093
Part05-风哥经验总结与分享
5.1 最佳实践
最佳实践:
## 1. 基线建立最佳实践
– 选择合适的采集时间:选择系统正常运行的时间段
– 采集足够的数据:采集至少7天的数据,覆盖不同的业务场景
– 分析全面的指标:分析所有关键性能指标
– 确定合理的基线值:基于统计分析确定基线值
– 定期更新基线:根据系统变化和业务需求定期更新基线
## 2. 指标采集最佳实践
– 使用标准化的采集工具:使用Prometheus、Node Exporter等标准工具
– 配置合理的采集频率:根据指标重要性设置不同的采集频率
– 采集全面的指标:采集系统、数据库、业务等各方面的指标
– 确保数据质量:确保采集的数据准确、完整
– 存储足够的历史数据:存储足够的历史数据,便于趋势分析
## 3. 基线监控最佳实践
– 实时监控:实时监控系统性能指标
– 与基线比较:将实时指标与基线进行比较
– 设置合理的告警阈值:根据基线设置合理的告警阈值
– 多维度监控:从不同维度监控系统性能
– 可视化展示:使用Grafana等工具可视化展示监控数据
## 4. 性能优化最佳实践
– 基于基线优化:根据基线分析结果进行性能优化
– 持续优化:持续监控和优化系统性能
– 验证优化效果:通过对比优化前后的性能指标验证优化效果
– 文档化优化过程:记录优化过程和结果
– 分享优化经验:分享优化经验和最佳实践
## 5. 团队协作最佳实践
– 明确责任分工:明确团队成员在性能基线建立和监控中的职责
– 建立工作流程:建立性能基线建立和监控的工作流程
– 定期回顾:定期回顾性能基线和监控效果
– 培训学习:定期对团队成员进行培训
– 知识共享:共享性能基线建立和监控的经验和最佳实践
5.2 常见问题与解决方案
常见问题与解决方案:
## 1. 基线建立问题
### 问题1:基线数据采集不足
– 原因:采集时间过短,或采集频率过低
– 解决方案:延长采集时间,增加采集频率
### 问题2:基线值不合理
– 原因:数据分析不全面,或业务场景变化
– 解决方案:重新分析数据,考虑业务场景变化
### 问题3:基线更新不及时
– 原因:没有定期更新基线,或系统变化后未及时更新
– 解决方案:建立基线更新机制,定期更新基线
## 2. 指标采集问题
### 问题1:指标采集失败
– 原因:采集工具配置错误,或网络连接问题
– 解决方案:检查采集工具配置,确保网络连接正常
### 问题2:指标数据不准确
– 原因:采集工具版本不兼容,或配置不当
– 解决方案:使用兼容的采集工具版本,正确配置采集参数
### 问题3:指标数据丢失
– 原因:存储配置不当,或磁盘空间不足
– 解决方案:调整存储配置,确保磁盘空间充足
## 3. 基线监控问题
### 问题1:告警误报
– 原因:告警阈值设置不合理,或基线值不准确
– 解决方案:调整告警阈值,重新确定基线值
### 问题2:告警漏报
– 原因:监控覆盖不全面,或告警规则配置不当
– 解决方案:增加监控覆盖,调整告警规则
### 问题3:监控性能问题
– 原因:监控数据量过大,或查询语句复杂
– 解决方案:优化监控数据存储,简化查询语句
5.3 未来发展
未来发展:
## 1. 智能化发展
– 智能基线:使用AI技术自动建立和调整基线
– 智能告警:使用AI技术减少误报和漏报
– 智能优化:使用AI技术自动优化系统性能
– 智能预测:使用AI技术预测系统性能变化
– 智能分析:使用AI技术分析性能数据
## 2. 自动化发展
– 自动采集:自动采集和分析性能数据
– 自动基线:自动建立和更新性能基线
– 自动告警:自动设置和调整告警阈值
– 自动优化:自动识别和优化性能瓶颈
– 自动报告:自动生成性能报告
## 3. 可视化发展
– 3D可视化:使用3D技术可视化性能数据
– 实时可视化:实时展示性能数据
– 交互式可视化:提供交互式性能分析工具
– 多维度可视化:从多个维度可视化性能数据
– 移动可视化:支持移动设备访问性能监控
## 4. 集成发展
– 多云集成:支持多云环境的性能监控
– 边缘计算集成:支持边缘计算环境的性能监控
– IoT集成:支持物联网设备的性能监控
– 区块链集成:支持区块链系统的性能监控
– DevOps集成:与DevOps工具链集成
## 5. 行业应用发展
– 金融行业:实时监控和风险控制
– 制造业:设备监控和预测维护
– 电商行业:业务监控和用户体验优化
– 医疗行业:患者数据处理性能监控
– 交通行业:交通系统性能监控和优化
本文由风哥教程整理发布,仅用于学习测试使用,转载注明出处:http://www.fgedu.net.cn/10327.html
