如何实现用prometheus+grafana实时监控mysql数据库?
概述
Prometheus 服务本地已经启动了,接下来,需要安装并运行 Exporter,它的主要作用是持续输出监控的组件信息并格式化,同时提供 Http 接口供 Prometheus 服务来抓取。Exporter 也是通过 GO 语言编写的,Prometheus GitHub 已经为我们提供了很多实用的 Exporter,直接拿来使用即可。
前面已经分享了编译安装和docker安装prometheus的两种方式,今天主要介绍下怎么用prometheus来监控mysql数据库。
一、安装go语言环境
由于Prometheus 是用golang开发的,所以首先安装一个go环境,Go语言是跨平台,支持Windows、Linux、Mac OS X等系统,还提供有源码,可编译安装。
下载地址:
https://studygolang.com/dl
1、解压
# tar -xvf go1.13.linux-amd64.tar.gz -C /usr/local/

2、配置环境变量
echo "export PATH=$PATH:/usr/local/go/bin" >> /etc/profile source /etc/profile

3、测试
验证一下是否成功,用go version 来验证
# go version

二、安装mysqld_exporter
1、下载node_exporter
官网地址:
https://prometheus.io/download/
下载地址:
https://github.com/prometheus/mysqld_exporter/releases/download/v0.12.1/mysqld_exporter-0.12.1.linux-amd64.tar.gz


2、上传解压
上传到被监控的主机并解压
tar -xvf mysqld_exporter-0.12.1.linux-amd64.tar.gz -C /usr/local/

3、配置监控数据库账号
配置要监控的数据库,为 mysql_exporter 创建一个指定账户用来连接数据库(当然,也可以直接用 root 或者其他有权限的账户,不过建议创建一个专有账户)。
CREATE USER exporter@'localhost' IDENTIFIED BY 'xxxx' WITH MAX_USER_CONNECTIONS 3; GRANT PROCESS, REPLICATION CLIENT, SELECT ON *.* TO exporter@'localhost';
4、启动Exporter
需要配置一下数据库连接认证信息并启动 Exporter,有两种方式配置:
4.1、使用环境变量方式(推荐)
export DATA_SOURCE_NAME='exporter:fswl@1234@(localhost:3306)/' ./mysqld_exporter

4.2、使用配置文件方式
# vim ~/.my.cnf [client] host=localhost port=3306 user=exporter password=password # ./mysqld_exporter
注意:mysqld_exporter 默认使用 ~/.my.cnf 作为数据库认证文件,如果我们指定其他路径文件,需要启动时指定路径,例如:./mysqld_exporter --config.my-cnf="<file_path>/.my.cnf"。
5、测试访问
此时,本地浏览器访问 http://服务器ip:9104/metrics 可以看到 mysql 相关的所有监控指标列表。

三、关联Prometheus
Prometheus 和 mysqld_exporter 服务都已经启动起来了,那么接下来就需要将二者关联起来,让 Prometheus 来定时抓取 Exporter 提供的数据。我们需要修改 Prometheus 的配置文件 prometheus.yml 增加 mysql 相关 exporter job。
说明一下:增加了一个 job_name 为 mysql 的任务,targets 为指向 mysqld_exporter 提供的 Http 接口服务,labels 为该 job 配置一个标签,方便下边 Grafana 页面显示
- job_name: mysql static_configs: - targets: ['xx.xx.xx.xx:9104'] labels: instance: epms_mysql

重启容器,隔一会查看metris:

四、grafana配置
1、下载dashboard
在
https://grafana.com/dashboards?search=mysql 下载mysql相关的dashboard,但是上边提供的dashboard效果不一定好,可以根据需要自己配.

2、导入json

3、展示


