SpringBoot整合Prometheus

SpringBoot整合Prometheus

本文基于SpringBoot2.5.7整合Prometheus,整合依赖micrometer相关包,上报到prometheus有两种方式:

  1. 基于Pushgateway 方式上报数据到prometheus,作为网关支持多个应用上报,需要推送数据到prometheus
  2. 作为一个独立应用上报到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());
    }
}
  • 2
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值