Springboot2的acutator已经默认提供了prometheus调用的接口,引入相关的pom即可自动配置。
pom文件片段
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</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的监控机制-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
application.yml
# http://localhost:7777/Prometheus
management:
#server:
#port: 7777 #不单独设置端口的话,和服务的端口一致
#servlet:
#context-path: /boot
endpoints:
web:
exposure:
include: "*"
base-path: / # 访问路径中没有actuator 直接是http://localhost:8080/Prometheus
server:
tomcat:
uri-encoding: UTF-8
max-threads: 1000
min-spare-threads: 30
port: 8080
经过上面的配置,启动Springboot项目,通过http://172.16.13.10:8080/prometheus已经可以访问Springboot内部定义的一些meter(统计数据)了,但是全是一些文字信息,极不友好。此时需要通过一个第三方工具来解析这些统计信息,Prometheus就是这样一类工具,通过从调用Springboot提供的acutator接口来拉取相关的统计数据进行分析和展示。
Centos7安装Prometheus
- 下载
http://cactifans.hi-www.com/prometheus/prometheus-2.1.0.linux-amd64.tar.gz - 执行命令安装
prometheus安装比较简单,下载编译好的二进制文件,修改好配置文件,直启动即可。
tar -zxvf prometheus-2.1.0.linux-amd64.tar.gz
mv prometheus-2.1.0.linux-amd64 /usr/local/prometheus - 启动
cd /usr/local/prometheus
./prometheus --config.file=prometheus.yml
将Springboot接入到Prometheus
修改/usr/local/prometheus/prometheus.yml
- job_name: 'my_demo'
metrics_path: '/prometheus'
# scheme defaults to 'http'.
static_configs:
- targets: ['172.16.13.10:8080']
访问Prometheus
启动Prometheus(默认端口为9090)和Springboot项目
访问:http://ip:9090/targets会显示如下的界面,表示接入成功

image.png
Springboot2中自定义meter
Prometheus除了可以获取Springboot2中内置的meter之外,还可以获取用户自定义的meter
- 引入MeterRegistry
@Configuration
public class MicrometerRegistry {
@Bean
MeterRegistryCustomizer<MeterRegistry> meterRegistryCustomizer() {
return registry -> registry.config().commonTags("tag1", "a", "tag2", "b");
}
}
- 引入meter(以Counter为例)
实现的功能为:访问"/test"一次计数器增加1
@RestController
@RequestMapping(value = "/micrometer")
public class TestController {
private Counter counter;
public TestController(MeterRegistry meterRegistry) {
this.counter = meterRegistry.counter("greeting");
}
@RequestMapping(value = "/test", method = RequestMethod.POST)
public String test() {
this.counter.increment();
return "hello world #" + this.counter.count();
}
}