linux 使用 MySQL Performance Schema 和 Prometheus + Grafana 来监控 MySQL 性能

🎯 方案 1:使用 MySQL Performance Schema

Performance Schema 是 MySQL 内置的性能监控工具,适合排查慢查询、锁等待、资源使用等问题。

步骤 1:启用 Performance Schema

1️⃣ 在 MySQL 配置文件中(通常是 /etc/mysql/my.cnf/etc/mysql/mysql.conf.d/mysqld.cnf),启用 Performance Schema

[mysqld]
performance_schema = ON

2️⃣ 重启 MySQL 服务:

sudo systemctl restart mysql

3️⃣ 登录到 MySQL,确认 Performance Schema 已启用:

mysql -u root -p

执行以下命令:

SHOW VARIABLES LIKE 'performance_schema';

步骤 2:查询常用的 Performance Schema 表

1️⃣ 查看 活跃的连接和查询

SELECT * FROM performance_schema.events_statements_current;

2️⃣ 查看 慢查询统计

SELECT * FROM performance_schema.events_statements_summary_by_digest ORDER BY COUNT_STAR DESC LIMIT 10;

3️⃣ 查看 锁等待时间

SELECT * FROM performance_schema.events_waits_summary_global_by_event_name;

🎯 方案 2:使用 Prometheus + Grafana 监控 MySQL

步骤 1:安装 Prometheus 和 Grafana

➡️ 1. 在 Linux 上安装 Prometheus
sudo apt update
sudo apt install prometheus
➡️ 2. 安装 Grafana
sudo apt install grafana

启动 Grafana:

sudo systemctl start grafana-server

访问 Grafana Web 界面:

http://localhost:3000

默认登录:

  • 用户名:admin
  • 密码:admin

步骤 2:安装 MySQL Exporter

Prometheus 需要一个 MySQL Exporter 来收集 MySQL 的性能数据。

➡️ 1. 下载并配置 MySQL Exporter
wget https://github.com/prometheus/mysqld_exporter/releases/download/v0.14.0/mysqld_exporter-0.14.0.linux-amd64.tar.gz
tar xzf mysqld_exporter-0.14.0.linux-amd64.tar.gz
cd mysqld_exporter-0.14.0.linux-amd64
➡️ 2. 创建 MySQL 用户

在 MySQL 中创建一个用户来访问 Performance Schema

CREATE USER 'exporter'@'localhost' IDENTIFIED BY 'your_password';
GRANT PROCESS, REPLICATION CLIENT, SELECT ON *.* TO 'exporter'@'localhost';
FLUSH PRIVILEGES;
➡️ 3. 启动 MySQL Exporter
./mysqld_exporter --config.my-cnf="/path/to/.my.cnf"

步骤 3:配置 Prometheus

编辑 Prometheus 的配置文件 prometheus.yml,添加 MySQL Exporter:

scrape_configs:
  - job_name: 'mysql'
    static_configs:
      - targets: ['localhost:9104']

重启 Prometheus

sudo systemctl restart prometheus

步骤 4:配置 Grafana

1️⃣ 在 Grafana Web 界面中,添加 Prometheus 作为数据源。

2️⃣ 导入现成的 MySQL 监控仪表板 模板(ID: 7362)。


最终效果

  • 通过 Grafana,可以实时查看 MySQL 查询性能、慢查询、连接数、缓存命中率、磁盘 I/O 等关键指标。

  • 可以设置告警,及时发现 查询延迟、磁盘空间不足 等问题。


⚙️ 常用 Prometheus + Grafana MySQL 监控指标

指标说明
mysql_global_status全局 MySQL 状态
mysql_upMySQL 是否正常运行
mysql_global_variablesMySQL 全局变量
mysql_queries_per_second每秒查询次数
mysql_slow_queries慢查询次数

🛠 总结

方案适用场景
Performance Schema轻量级性能分析工具
Prometheus + Grafana实时监控和告警
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

十方来财

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值