MySQL监控体系搭建:常用监控工具、核心监控指标,实时掌控数据库状态

张开发
2026/4/5 15:14:28 15 分钟阅读

分享文章

MySQL监控体系搭建:常用监控工具、核心监控指标,实时掌控数据库状态
MySQL监控体系搭建常用监控工具、核心监控指标实时掌控数据库状态一套完善的监控体系是保障MySQL稳定运行的基石。本文将从工具选型、核心指标、实战部署三个维度分享如何搭建企业级的MySQL监控体系。一、监控工具选型对比1.1 主流开源工具全景图工具定位核心优势适用场景Prometheus Grafana云原生监控标准强大的时序存储、灵活的查询语言、丰富的生态容器化/K8s环境、需要自定义看板Percona Monitoring and Management (PMM)MySQL专属方案开箱即用、深度MySQL优化、Query AnalyticsMySQL/MongoDB/PostgreSQL混合环境Zabbix传统监控平台成熟稳定、告警机制完善、支持多协议传统企业IT基础设施MySQL Enterprise Monitor官方商业方案官方支持、深度集成、安全审计有预算的企业核心系统InfluxDB Telegraf高性能时序方案写入性能高、保留策略灵活超大规模指标采集1.2 深度对比Prometheus vs PMMPrometheus方案架构MySQL Exporter → Prometheus Server → Grafana Dashboard ↑ ↑ ↑ 采集指标 时序存储/告警 可视化展示PMM方案架构pmm-agent (部署在DB节点) → pmm-server (集中管理) ↑ 内置QAN慢查询分析 深度MySQL指标选型建议云原生团队 →Prometheus Grafana灵活可控专注MySQL深度优化 →PMM慢查询分析是杀手锏已有Zabbix基础设施 → 扩展MySQL模板降低迁移成本二、核心监控指标体系2.1 四层监控模型┌─────────────────────────────────────────┐ │ Layer 4: 业务层 (Business) │ │ - QPS/TPS、查询响应时间、错误率 │ ├─────────────────────────────────────────┤ │ Layer 3: 连接层 (Connection) │ │ - 线程状态、连接数、Aborted连接 │ ├─────────────────────────────────────────┤ │ Layer 2: 存储引擎层 (Engine) │ │ - InnoDB事务、锁等待、Buffer Pool命中率 │ ├─────────────────────────────────────────┤ │ Layer 1: 系统资源层 (OS) │ │ - CPU、内存、磁盘I/O、网络 │ └─────────────────────────────────────────┘2.2 关键指标详解与告警阈值 系统资源层基础保障指标采集方式告警阈值说明CPU使用率top/vmstat 70% 警告 85% 严重注意iowait占比内存使用率free -m 80% 警告关注OOM风险磁盘I/O利用率iostat -x 1 80% 警告%util字段磁盘空间使用率df -h 80% 警告 90% 严重包含binlog空间网络延迟ping/tcprstat 10ms 警告影响主从复制PromQL示例磁盘I/O# 磁盘读取延迟 rate(node_disk_read_time_seconds_total[5m]) / rate(node_disk_reads_completed_total[5m]) # 磁盘写入延迟 rate(node_disk_write_time_seconds_total[5m]) / rate(node_disk_writes_completed_total[5m]) 连接层流量入口指标SQL查询告警阈值优化建议活跃连接数SHOW STATUS LIKE Threads_connected max_connections * 80%检查连接池配置运行线程数SHOW STATUS LIKE Threads_running 50 警告视硬件而定可能慢查询堆积连接创建速率SHOW STATUS LIKE Threads_created持续增长需关注考虑增大thread_cache_sizeAborted_connectsSHOW STATUS LIKE Aborted_connects突增需排查检查网络/认证问题关键诊断SQL-- 查看当前连接状态分布SELECTuser,db,command,state,COUNT(*)ascnt,GROUP_CONCAT(INFO SEPARATOR\n)assample_queriesFROMinformation_schema.processlistWHEREcommand!SleepGROUPBYuser,db,command,stateORDERBYcntDESC;-- 查看连接来源IP分布SELECTSUBSTRING_INDEX(host,:,1)asclient_ip,COUNT(*)asconnectionsFROMinformation_schema.processlistGROUPBYclient_ip; 存储引擎层InnoDB核心事务与锁监控-- 查看活跃事务排查长事务SELECTtrx_id,trx_mysql_thread_id,trx_state,TIMESTAMPDIFF(SECOND,trx_started,NOW())astrx_seconds,LEFT(trx_tables_locked,50)astables_locked,LEFT(trx_tables_in_use,50)astables_in_useFROMinformation_schema.innodb_trxORDERBYtrx_started;-- 查看锁等待排查死锁SELECTr.trx_idaswaiting_trx,r.trx_mysql_thread_idaswaiting_thread,b.trx_idasblocking_trx,b.trx_mysql_thread_idasblocking_thread,w.lock_modeaswaiting_lock,b.lock_modeasblocking_lockFROMinformation_schema.innodb_lock_waits wJOINinformation_schema.innodb_trx bONb.trx_idw.blocking_trx_idJOINinformation_schema.innodb_trx rONr.trx_idw.requesting_trx_id;Buffer Pool命中率-- 计算Buffer Pool命中率SELECT(1-(SELECTVARIABLE_VALUEFROMperformance_schema.global_statusWHEREVARIABLE_NAMEInnodb_buffer_pool_reads)/(SELECTVARIABLE_VALUEFROMperformance_schema.global_statusWHEREVARIABLE_NAMEInnodb_buffer_pool_read_requests))*100ashit_ratio;告警阈值 95% 警告 90% 严重考虑增大buffer pool关键InnoDB指标指标查询方式健康标准Buffer Pool命中率上述SQL计算 95%每秒脏页刷新SHOW STATUS LIKE Innodb_data_writes平稳无突增日志写入等待SHOW STATUS LIKE Innodb_log_waits接近0行锁等待次数SHOW STATUS LIKE Innodb_row_lock_waits低频率自适应哈希索引使用率SHOW ENGINE INNODB STATUS视工作负载 业务层核心SLAQPS/TPS计算-- 计算QPS每秒查询数SHOWGLOBALSTATUSLIKEQueries;-- 差值计算-- 更精确的Com_*统计SELECTSUM(variable_value)astotal_commandsFROMperformance_schema.global_statusWHEREvariable_nameLIKECom_%;慢查询分析PMM QAN核心-- 开启慢查询日志动态SETGLOBALslow_query_logON;SETGLOBALlong_query_time1;-- 1秒阈值SETGLOBALlog_outputTABLE;-- 输出到表便于分析-- 分析慢查询mysql.slow_log表SELECTsql_text,COUNT(*)asexec_count,AVG(query_time)asavg_time,MAX(query_time)asmax_time,SUM(lock_time)astotal_lock_timeFROMmysql.slow_logWHEREstart_timeDATE_SUB(NOW(),INTERVAL1HOUR)GROUPBYsql_textORDERBYavg_timeDESCLIMIT10;三、实战部署Prometheus Grafana方案3.1 架构设计┌─────────────┐ │ Grafana │ │ (可视化) │ └──────┬──────┘ │ ┌──────▼──────┐ │ Prometheus │ │ (时序数据库) │ └──────┬──────┘ │ ┌──────────────────┼──────────────────┐ │ │ │ ┌────▼────┐ ┌────▼────┐ ┌────▼────┐ │ mysqld │ │ mysqld │ │ mysqld │ │exporter │ │exporter │ │exporter │ └────┬────┘ └────┬────┘ └────┬────┘ │ │ │ ┌────▼────┐ ┌────▼────┐ ┌────▼────┐ │ MySQL │ │ MySQL │ │ MySQL │ │ Primary │◄─────►│ Replica │◄─────►│ Replica │ └─────────┘ └─────────┘ └─────────┘ │ ┌────▼────┐ │node │ │exporter │ ← 采集OS指标 └─────────┘3.2 部署步骤Step 1: 部署mysqld_exporter# 下载安装wgethttps://github.com/prometheus/mysqld_exporter/releases/download/v0.15.0/mysqld_exporter-0.15.0.linux-amd64.tar.gztarxvfz mysqld_exporter-*.tar.gzsudomvmysqld_exporter-*/mysqld_exporter /usr/local/bin/# 创建监控用户最小权限原则CREATEUSERexporterlocalhostIDENTIFIED BYStrongPasswordWITH MAX_USER_CONNECTIONS3;GRANT PROCESS, REPLICATION CLIENT, SELECT ON *.* TOexporterlocalhost;# 配置.my.cnfcat/etc/.mysqld_exporter.cnfEOF [client] userexporter passwordStrongPassword hostlocalhost port3306 EOF# Systemd服务cat/etc/systemd/system/mysqld_exporter.serviceEOF [Unit] DescriptionMySQL Prometheus Exporter Afternetwork.target [Service] Typesimple Userprometheus ExecStart/usr/local/bin/mysqld_exporter \ --config.my-cnf/etc/.mysqld_exporter.cnf \ --collect.global_status \ --collect.info_schema.innodb_metrics \ --collect.info_schema.processlist \ --collect.info_schema.tablestats \ --collect.info_schema.userstats \ --collect.perf_schema.tablelocks \ --collect.perf_schema.file_events \ --collect.perf_schema.eventswaits \ --collect.perf_schema.indexiowaits \ --collect.perf_schema.tableiowaits \ --collect.slave_status Restartalways [Install] WantedBymulti-user.target EOFsystemctlenable--nowmysqld_exporterStep 2: Prometheus配置# /etc/prometheus/prometheus.ymlscrape_configs:-job_name:mysqlstatic_configs:-targets:-db1.example.com:9104-db2.example.com:9104-db3.example.com:9104relabel_configs:-source_labels:[__address__]target_label:instanceregex:([^:]):.*replacement:${1}-job_name:nodestatic_configs:-targets:-db1.example.com:9100-db2.example.com:9100Step 3: 关键告警规则AlertManager# /etc/prometheus/rules/mysql.ymlgroups:-name:mysql_alertsrules:# MySQL宕机-alert:MySQLDownexpr:mysql_up 0for:1mlabels:severity:criticalannotations:summary:MySQL实例宕机 {{ $labels.instance }}# 连接数过高-alert:MySQLTooManyConnectionsexpr:|( mysql_global_status_threads_connected / mysql_global_variables_max_connections * 100 ) 80for:5mlabels:severity:warningannotations:summary:MySQL连接数过高 {{ $labels.instance }}# 慢查询突增-alert:MySQLSlowQueriesRisingexpr:|rate(mysql_global_status_slow_queries[5m]) 10for:5mlabels:severity:warningannotations:summary:慢查询速率突增 {{ $labels.instance }}# 复制延迟-alert:MySQLReplicationLagexpr:|mysql_slave_lag_seconds 30for:5mlabels:severity:warningannotations:summary:主从复制延迟过高 {{ $labels.instance }}# InnoDB日志等待-alert:MySQLInnodbLogWaitsexpr:|rate(mysql_global_status_innodb_log_waits[5m]) 10for:5mlabels:severity:warningannotations:summary:InnoDB日志写入等待 {{ $labels.instance }}3.3 Grafana看板关键面板1. 实例概览面板Row 1单实例QPS/TPS趋势图连接数使用百分比Gauge图Buffer Pool命中率Gauge图2. 查询性能面板Row 2慢查询数量/速率查询响应时间P99/P95/P50分布Top 10慢查询指纹配合PMM或日志分析3. 存储引擎面板Row 3InnoDB读写IO吞吐量脏页比例 vs 刷新速率行锁等待次数/时间4. 复制状态面板Row 4复制延迟秒数IO线程/SQL线程状态主从Exec_Master_Log_Pos差距四、高级监控技巧4.1 自动发现与标签管理# 基于文件的服务发现-job_name:mysql-file-sdfile_sd_configs:-files:-/etc/prometheus/mysql-targets.jsonrefresh_interval:5mrelabel_configs:# 从标签提取环境信息-source_labels:[__meta_custom_env]target_label:env-source_labels:[__meta_custom_role]target_label:role# primary/replica4.2 自定义业务指标采集通过events_statements_summary_by_digest实现Query指纹分析-- 创建视图便于Prometheus采集CREATEVIEWquery_statsASSELECTDIGEST_TEXTasquery_pattern,COUNT_STARasexec_count,AVG_TIMER_WAIT/1000000000asavg_latency_ms,MAX_TIMER_WAIT/1000000000asmax_latency_ms,SUM_ROWS_SENTastotal_rows_sent,SUM_ROWS_EXAMINEDastotal_rows_examined,SUM_CREATED_TMP_TABLESastmp_tablesFROMperformance_schema.events_statements_summary_by_digestORDERBYAVG_TIMER_WAITDESCLIMIT100;4.3 监控体系健康自检#!/bin/bash# check_monitoring_health.sh# 定期检查监控链路自身健康# 1. 检查exporter可访问性forhostindb1 db2 db3;doif!curl-shttp://${host}:9104/metrics|grep-qmysql_up;thenechoCRITICAL: mysqld_exporter on$hostnot responding# 发送告警到备用通道短信/电话fidone# 2. 检查Prometheus数据新鲜度if!curl-shttp://prometheus:9090/api/v1/query?queryup|grep-qsuccess;thenechoCRITICAL: Prometheus query API failedfi# 3. 检查AlertManager静默状态curl-shttp://alertmanager:9093/api/v1/silences|jq.data[] | select(.status.stateactive)五、总结与最佳实践监控体系搭建 checklist分层监控OS → Engine → Connection → Business 四层覆盖指标取舍采集100指标但告警只聚焦20个核心指标基线建立收集至少7天数据建立正常范围基线告警分级Warning关注→ Critical立即处理→ Emergency自动降级可视化Dashboard服务于不同角色DBA关注细节老板关注SLA持续优化每月Review告警有效性消除误报推荐演进路径阶段10-1个月部署基础监控PrometheusGrafana覆盖宕机/连接数/磁盘 阶段21-3个月完善引擎层监控接入慢查询分析 阶段33-6个月建立容量预测模型实现自动化告警降噪 阶段46个月基于监控数据驱动优化索引优化、参数调优监控不是目的而是手段。最终目标是在故障发生前发现趋势在影响业务前完成干预。本文基于MySQL 8.0和Prometheus 2.40实践验证生产环境请根据实际规模调整采集频率和 retention 策略。希望这篇实战指南能帮助你快速搭建起企业级的MySQL监控体系。如果有具体的部署问题或指标调优需求欢迎继续讨论。

更多文章