深色模式
数据库监控指标
摘要:数据库监控抓四类信号:存活、资源(连接/内存/磁盘)、性能(QPS/慢查询/锁)、复制状态。本文给出各库必看指标、建议阈值与 Prometheus exporter 接入方式。
适用环境
bash
# 已有 Prometheus;准备部署对应 exporter
prometheus --version
ss -lntp | grep -E '9104|9187|9121' # mysqld_exporter / postgres_exporter / redis_exporter1
2
3
2
3
操作步骤
1. 部署 exporter
bash
# MySQL
mysqld_exporter --config.my-cnf=/etc/.mysqld_exporter.cnf --web.listen-address=:9104
# PostgreSQL
DATA_SOURCE_NAME="postgresql://postgres:密码@localhost:5432/postgres?sslmode=disable" postgres_exporter --web.listen-address=:9187
# Redis
redis_exporter --redis.addr=redis://localhost:6379 --redis.password='密码' --web.listen-address=:91211
2
3
4
5
6
2
3
4
5
6
2. Prometheus 抓取配置
yaml
# prometheus.yml
scrape_configs:
- job_name: 'mysql'
static_configs:
- targets: ['10.0.1.10:9104']
- job_name: 'redis'
static_configs:
- targets: ['10.0.1.30:9121']1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
3. 必看指标与建议阈值
| 类别 | 指标 | 建议告警 |
|---|---|---|
| 存活 | mysql_up / pg_up / redis_up | == 0 立即告警(P1) |
| 连接 | 连接数 / max_connections | > 80% 持续 5 分钟 |
| 性能 | 慢查询数/秒 | 突增 3 倍或持续 > 10/s |
| 资源 | 磁盘使用率 | > 80% 预警,> 90% 紧急 |
| 复制 | 主从延迟秒数 | > 30s 预警,> 300s 紧急 |
| 锁 | InnoDB 行锁等待时长 | > 5s 持续出现 |
4. 用命令行直接取指标(临时排查)
bash
# MySQL 关键状态
mysql -uroot -p -e "SHOW GLOBAL STATUS LIKE 'Threads_connected'; \
SHOW GLOBAL STATUS LIKE 'Questions'; SHOW GLOBAL STATUS LIKE 'Slow_queries';"
# Redis
redis-cli -a '密码' INFO stats | grep -E 'instantaneous_ops_per_sec|connected_clients'
redis-cli -a '密码' INFO memory | grep used_memory_human
# PostgreSQL
psql -U postgres -c "SELECT count(*), state FROM pg_stat_activity GROUP BY state;"1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
5. 计算 QPS 的小脚本
bash
#!/usr/bin/env bash
# qps.sh:间隔 1 秒采样两次 Questions 差值
a=$(mysql -uroot -p"$1" -N -e "SHOW GLOBAL STATUS LIKE 'Questions'" | awk '{print $2}')
sleep 1
b=$(mysql -uroot -p"$1" -N -e "SHOW GLOBAL STATUS LIKE 'Questions'" | awk '{print $2}')
echo "QPS=$((b-a))"1
2
3
4
5
6
2
3
4
5
6
6. 告警规则示例
yaml
groups:
- name: mysql
rules:
- alert: MySQLDown
expr: mysql_up == 0
for: 1m
labels: { severity: critical }
- alert: MySQLReplicationLag
expr: mysql_slave_status_seconds_behind_master > 300
for: 5m
labels: { severity: warning }1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
危险
告警阈值不要照抄。先用一到两周观察基线(P99 值),再按业务容忍度设定,否则会产生大量无效告警导致告警疲劳。
验证
bash
curl -s http://localhost:9104/metrics | grep mysql_up
curl -s http://localhost:9090/api/v1/query --data-urlencode 'query=mysql_up'
# 停止一次实例,确认告警能触发并收到通知1
2
3
2
3
常见坑
WARNING
exporter 用的账号权限要最小化(MySQL 只需 PROCESS, REPLICATION CLIENT, SELECT),不要用 root。
WARNING
监控采集间隔过密(如 5s)会给数据库带来额外查询压力,一般 15~60s 足够。
DANGER
exporter 暴露的 metrics 接口含实例信息,不要直接暴露到公网;用防火墙或反向代理鉴权保护。