基于 Prometheus 和 Grafana 实现对 SpringBoot 应用的监控
本文使用 Prometheus 和 Grafana 实现对 SpringBoot 应用服务、数据库监控的简单实现。首先,Prometheus 是一个开源的完整监控解决方案,其对传统监控系统的测试和告警模型进行了彻底的颠覆,形成了基于中央化的规则计算、统一分析和告警的新模型,而 Grafana 是一款采用 go 语言编写的开源应用,主要用于大规模指标数据的可视化展现,是网络架构和应用分析中最流行的时序数据展示工具。两者的结合构成了一款主流前沿的开源监控和报警系统。
1、新建 SpringBoot 项目
添加依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-prometheus</artifactId>
<version>1.9.5</version>
</dependency>
复制代码
添加配置:
spring:
application:
name: springboot_web
management:
endpoint:
prometheus:
enabled: true
endpoints:
web:
exposure:
include: "*"
metrics:
export:
prometheus:
step: 10s
enabled: true
tags:
application: ${spring.application.name}
复制代码
2、对 MySQL 数据库进行监控
2.1 下载 mysqld_exporter (https://prometheus.io/download/#mysqld_exporter)
2.2 配置访问账号文件:mysqld_exporter.my.cnf
[client]
user=root
password=PetterW0ng
复制代码
2.3 启动 mysqld_exporter
mysqld_exporter.exe --config.my-cnf="mysqld_exporter.my.cnf"
复制代码
3、使用 Docker Compose 形式部署 Prometheus 、Grafana
3.1 docker-compose.yml 配置文件如下:
version: '3'
services:
grafana:
container_name: grafana
image: grafana/grafana
environment:
- TZ=Asia/Shanghai
ports:
- 3000:3000
volumes:
- ./grafanaplugin:/var/lib/grafana/plugins/grafanaplugin
- ./grafana.ini:/usr/share/grafana/conf/defaults.ini
privileged: true
restart: always
prometheus:
container_name: prometheus
image: quay.io/prometheus/prometheus:latest
volumes:
- ./prometheus.yml:/etc/prometheus/prometheus.yml
command: "--config.file=/etc/prometheus/prometheus.yml --storage.tsdb.path=/prometheus"
ports:
- "9090:9090"
复制代码
3.2 prometheus.yml 配置如下:
scrape_configs:
- job_name: 'actuator-springboot'
scrape_interval: 15s
scrape_timeout: 10s
metrics_path: '/actuator/prometheus'
static_configs:
- targets: ['IP:9001']
- job_name: 'mysql'
scrape_interval: 15s
scrape_timeout: 10s
static_configs:
- targets: ['IP:9104']
复制代码
3.3 grafana.ini 里面设置邮箱相关配置
#################################### SMTP / Emailing #####################
[smtp]
enabled = true
host = smtp.aliyun.com:465
user = xxxx@aliyun.com
# If the password contains # or ; you have to wrap it with triple quotes. Ex """#password;"""
password = xxxx
cert_file =
key_file =
skip_verify = false
from_address = xxxx@aliyun.com
from_name = Grafana
ehlo_identity =
startTLS_policy =
复制代码
4、在 Grafana 配置 Dashboard
4.1 登录 http://IP:3000 (admin : admin)
4.2 新建 Prometheus DataSource
4.3 新建/Import Dashboard, 引入 SpringBoot (12900) 和 MySQL (7362) 相关的 Dashborad (https://grafana.com/)
5、创建 Email 告警相关
集控 CPU 使用率,并触发告警
评论