准备

mysqld_exporter:采集 MySQL/MariaDB 数据库监控指标

prometheus:一个开源系统和服务监控系统

Grafana:开源的,拥有丰富 dashboard 和图表编辑的指标分析平台

以 Windows 平台作为演示

mysqld_exporter

1、下载

根据自己使用的平台选择合适的版本

下载地址:https://github.com/prometheus/mysqld_exporter/releases

Prometheus exporter for MySQL server metrics.

Supported versions:

  • MySQL >= 5.6.
  • MariaDB >= 10.3

NOTE: Not all collection methods are supported on MySQL/MariaDB < 5.6

2、配置用户

在需要监控的 MySQL 数据库创建一个专门用于监控的新用户,为该用户设置最大连接数为了避免监控数据过大导致服务器超载

用户名:exporter

密码:123456

1
CREATE USER 'exporter'@'localhost' IDENTIFIED BY '123456' WITH MAX_USER_CONNECTIONS 3;

权限:可查看主从运行情况查看线程,及所有数据库。

1
GRANT PROCESS, REPLICATION CLIENT, SELECT ON *.* TO 'exporter'@'localhost';

3、配置文件

在创建 .my.cnf 配置文件(注意 my 前面有.

Windows 平台的话, .my.cnf 放到软件启动目录;

Linux 平台的话,.my.cnf默认放置在启动用户的家目录,启动时无需指定;

也可以随意放置在任意目录,在启动时通过附加参数 --config.my-cnf={conf_dir}/.my.cnf指定配置文件

配置文件内容

1
2
3
4
5
[client]
user = exporter
password = 123456
host = 127.0.0.1
port = 3306

linux 设置自启动(备用)

1
vim /usr/lib/systemd/system/mysql_exporter.service

配置内容

1
2
3
4
5
6
7
8
9
10
11
12
13
[Unit]
Description=Prometheus
Wants=network-online.target
After=network-online.target

[Service]
User=root
Group=root
Type=simple
ExecStart=/usr/local/bin/mysqld_exporter

[Install]
WantedBy=multi-user.target

Windows 下通过 cmd 启动,浏览器访问:http://localhost:9104/

查看指标

prometheus

mysqld_exporter 搭建完成之后,数据并不直观,将其接入 prometheus 数据监控系统

1、下载

下载地址:https://github.com/prometheus/prometheus/releases

2、配置

下载完成以后,编辑 prometheus.yml 文件

加入 MySQL 的监控,作业名称 mysql,目标就是 mysqld_exporter 的地址:localhost:9104

1
2
3
4
5
6
7
8
9
10
11
12
13
scrape_configs:
# The job name is added as a label `job=<job_name>` to any timeseries scraped from this config.
- job_name: "prometheus"

# metrics_path defaults to '/metrics'
# scheme defaults to 'http'.

static_configs:
- targets: ["localhost:9090"]

- job_name: "mysql"
static_configs:
- targets: ["localhost:9104"]

随后直接通过 cmd 启动 prometheus.exe 即可

浏览器访问:http://localhost:9090/

可以看到监控已经在线了

Grafana

1、下载

下载地址:https://grafana.com/grafana/download?pg=get&plcmt=selfmanaged-box1-cta1

2、配置

进入软件的 bin目录,通过 cmd 启动 grafana-server.exe

浏览器访问:http://localhost:3000/

添加数据源为 prometheus

填写访问地址为:http://localhost:9090/

保存并测试

3、自定义面板

导入面板

直接搜索和 mysql 相关的面板:https://grafana.com/grafana/dashboards/?search=mysql

选择下载量第一的面板:https://grafana.com/grafana/dashboards/7362-mysql-overview/

载入

选择数据源

4、效果展示