在Kubernetes中用Prometheus监控SpringBoot Metrics

823 阅读1分钟
  1. 在SprintBoot 项目中添加引用
<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
        <groupId>io.micrometer</groupId>
        <artifactId>micrometer-registry-prometheus</artifactId>
        <version>1.1.4</version>
</dependency>

spring-boot-starter-actuator里面已经引用了micrometer-core micrometer-registry-prometheus的version最好和micrometer-core版本一致,否则可能出现metrics数据出不来

  1. 如果项目里面有 @EnableGlobalMethodSecurity, 添加以下代码, 否则jvm metrics可能不能加载
@Configuration
public class ActuatorConfig {

    @Bean
    InitializingBean forcePrometheusPostProcessor(BeanPostProcessor meterRegistryPostProcessor, PrometheusMeterRegistry registry) {
        return () -> meterRegistryPostProcessor.postProcessAfterInitialization(registry, "");
    }

}
  1. 在application.yml 中暴露metrics
management:
  server:
    port: 8102
  metrics:
    export:
      prometheus:
        enabled: true
    tags:
      application: ${spring.application.name}
  endpoint:
    metrics:
      enabled: true
    prometheus:
      enabled: true
  endpoints:
    web:
      exposure:
        include: 'health,prometheus,metrics'

port 建议和server.port暴露的端口不同, 这样server.port用来对外提供服务, management.server.port用于内部读取。 如果使用同样的端口, 建议加上security验证

  1. 本地测试 访问 http://localhost:8102/actuator/prometheus, 确认metrics数据能返回

  2. 给deployment添加annotation

spec:
  template:
    metadata:
      annotations:
        prometheus.io/scrape: "true"
        prometheus.io/port: "8102"
        prometheus.io/path: "/actuator/prometheus"
  1. 查看Prometheus的targets
  2. 添加Grafana dashboard 推荐Import grafana.com/grafana/das… 再添加自定义dashboard