SpringBoot整合Prometheus
本文基于SpringBoot2.5.7整合Prometheus,整合依赖micrometer相关包,上报到prometheus有两种方式:
- 基于Pushgateway 方式上报数据到prometheus,作为网关支持多个应用上报,需要推送数据到prometheus
- 作为一个独立应用上报到prometheus上报,但是修改prometheus配置文件,prometheus 拉取方式
本文将对这两种方式分别进行讲解,然后简单自定义实现metric上报prometheus。
springboot 实现自动装配可以看PrometheusMetricsExportAutoConfiguration,这个类实现了prometheus上报Pushgateway或者提供web url 供prometheus 来拉取
作为一个独立应用上报到prometheus
整合过程:
- 添加依赖
runtimeOnly 'io.micrometer:micrometer-registry-prometheus'
implementation 'org.springframework.boot:spring-boot-starter-actuator'
- 配置相关prometheus属性
management:
metrics:
tags:
application: ${spring.application.name}
export:
prometheus:
enabled: true
#开启暴露web
endpoints:
web:
exposure:
include: prometheus
spring:
application:
name: spring-boot-prometheus
-
查看结果
-
相关代码
@SpringBootApplication
public class PrometheusApplicationDemo {
public static void main(String[] args) {
SpringApplication.run(PrometheusApplicationDemo.class,args);
}
}
通过Pushgateway上报
整合过程:
- 添加依赖
runtimeOnly 'io.micrometer:micrometer-registry-prometheus'
implementation 'org.springframework.boot:spring-boot-starter-actuator'
implementation 'io.prometheus:simpleclient_pushgateway'
- 配置相关prometheus相关属性
management:
metrics:
tags:
application: ${spring.application.name}
export:
prometheus:
enabled: true
# pushgateway属性配置可以参考 https://github.com/prometheus/pushgateway
pushgateway:
enabled: true
base-url: http://192.168.41.101:9091/
job: ${spring.application.name}
grouping-key:
instance: 192.168.100.168
endpoints:
web:
exposure:
include: prometheus
spring:
application:
name: spring-boot-prometheus
- 查看结果
自定义Metrics数据上报到prometheus
官方文档见,使用起来很简单。比如我要统计调用/index 的总数,具体实现代码如下:
@RestController
public class HelloIndexController {
@Autowired
MycustomerMetricsBean mycustomerMetricsBean;
@RequestMapping("/index")
public String index() {
//每请求一次,counter 加1
mycustomerMetricsBean.getCounter().increment();
return "ok";
}
}
@Component
@Getter
@Setter
public class MycustomerMetricsBean {
private Counter counter;
//向MeterRegistry添加一个新的counter
public MycustomerMetricsBean(MeterRegistry registry) {
this.counter = registry.counter("hello-Index.size", Tags.empty());
}
}