Spring Boot+Prometheus+Grafana应用可视化监控

SpringBoot应用配置

本次搭建用的Springboot版本如下:

1
2
3
4
5
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
</parent>

首先在项目中添加以下依赖:

1
2
3
4
5
6
7
8
9
10
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

<dependency>
<groupId>io.prometheus</groupId>
<artifactId>simpleclient_spring_boot</artifactId>
<version>0.0.26</version>
</dependency>

在启动类 Application.java 中添加如下注解

1
2
3
4
5
6
7
8
9
10
@SpringBootApplication
@EnablePrometheusEndpoint
@EnableSpringBootMetricsCollector
public class Application {

public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}

}

最后在 application.yml 新增如下配置:

1
2
3
4
5
6
7
8
management:
security:
enabled: false #关掉安全认证
port: 8088 #管理端口调整成8088
context-path: /monitor #actuator的访问路径
endpoints:
shutdown:
enabled: true

这里单独开启了一个端口给监控服务,进行指标数据的获取。
启动应用后,可以看到新增了很多 /monitor/* 之类的Mappings,可以访问 http://127.0.0.1:8088/monitor/prometheus 查看到

Prometheus 采集 Spring Boot 指标数据

以下我们都将采用Docker来部署我们的监控服务,这里就不详细讲解Docker的安装使用
获取Prometheus的最新镜像

1
docker pull prom/prometheus

然后,编写配置文件 prometheus.yml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
global:
scrape_interval: 10s
scrape_timeout: 10s
evaluation_interval: 10m
scrape_configs:
- job_name: spring-boot
scrape_interval: 5s
scrape_timeout: 5s
metrics_path: /monitor/prometheus
scheme: http
basic_auth:
username: user
password: pwd
static_configs:
- targets:
- 47.96.121.21:8088

就在 prometheus.yml 文件目录,启动 Prometheus

1
docker run -d --name prometheus -p 9090:9090 -m 500M -v "$(pwd)/prometheus.yml":/prometheus.yml -v "$(pwd)/data":/data prom/prometheus --config.file=/prometheus.yml --log.level=info

最后,访问 http://localhost:9090/targets , 检查 Spring Boot 采集状态是否正常。

Grafana 可视化监控数据

获取 Grafana 的 Docker 镜像:

1
docker pull grafana/grafana

然后,启动 Grafana:

1
docker run --name grafana -d -p 3000:3000 grafana/grafana

接着,访问 http://localhost:3000/ 配置 Prometheus 数据源:

1
Grafana 登录账号 admin 密码 admin

配置 DataSource
https://upload-images.jianshu.io/upload_images/3424642-17cfb4ab6b48eab8.png
最后,配置单个指标的可视化监控面板:

选择 Graph
https://upload-images.jianshu.io/upload_images/3424642-7716afba5950b709.png
编辑

配置需要监控的指标

提示,此处不能任意填写,只能填已有的指标点,具体的可以在 Prometheus 的首页看到,即 http://localhost:9090/graph

多配置几个指标之后,即可有如下效果: