1、Spring boot2.x项目改造
在spring boot项目中添加 actuator、prometheus-core、micrometer-registry-prometheus(采集)maven, 并且需要注意版本关系(这里我spring boot的maven management使用了2.3.2但是引入的spring boot parent引入的是2.2.X导致整体引入的是 2.2.X但是prometheus还是1.5.3所有没有显示出来):
Spring boot 2.3.X 对应 micrometer-core、micrometer-registry-prometheus为1.5.X
Spring boot 2.4.X 对应 micrometer-core、micrometer-registry-prometheus为1.6.X
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-core</artifactId>
</dependency>
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-prometheus</artifactId>
</dependency>
在spring boot的yml(properties自行修改)中配置,可以配置值为 * 对所有开放,或者可以配置 prometheus,值对prometheus开放
management:
endpoints:
web:
exposure:
include: '*' # 或者填写 prometheus
# base-path: / # 访问路径中没有actuator 直接是http://ip:port/prometheus
metrics:
export:
prometheus:
enabled: true
tags:
application: ${spring.application.name} # 暴露的数据中添加application label
启动项目后访问: http://ip:port/prometheus
2、promethous安装和配置【基于docker】
docker安装过程省略,可以见之前的文档。拉去镜像:docker pull prom/prometheus
创建 /home/prometheus/prometheus.yml 配置文件,如下:
scrape_configs:
job_name: 'spring' # 多久采集一次数据
scrape_interval: 15s # 采集时的超时时间
scrape_timeout: 10s # 采集的路径
metrics_path: '/actuator/prometheus' #采集服务的地址,设置Springboot应用所在服务器
static_configs:
targets: ['127.0.0.1:9999']
使用docker命令进行启动:
说明:
- docker run prom/prometheus: 启动prometheus;
- -d:后台启动;
- -v: 将项目的目录挂载到docker的对应位置,需要注意 /home/prometheus/prometheus.yml是真实存在的配置文件地址
- --config.file: 执行prometheus的配置文件;
docker run -d -p 9090:9090 \
-v /home/prometheus/prometheus.yml:/etc/prometheus/prometheus.yml \
prom/prometheus \
--config.file=/etc/prometheus/prometheus.yml
查看是否已经安装正确的链接spring boot项目:
3、grafana安装和配置【基于docker】
还有用docker进行安装,拉取镜像: docker pull grafana/grafana
启动:docker run -d -p 3000:3000 grafana/grafana
并查看是否启动:docker ps| grep grafana
浏览器访问:http://ip:3000/ 用户名和密码都是 admin
添加 prometheus数据源,这里可以添加 mysql/gitlab等很多的数据源信息
Grafana允许三种方式添加 Dashboard,一个是直接下载好文件进行导入;一个是搜索到 id直接进行搜索添加;还可以直接输入json。 这个还是比较推荐直接使用id的方式,可以去网站:https://grafana.com/grafana/dashboards 选好后根据id进行添加。添加 Spring Boot Statistics 统计的模板,如下:
这里需要注意,spring boot的Dashboad区分1.x和2.x版本,否则就跟我开始一样搞了好久就是没有数据:
效果: