Skip to content

自定义度量指标

  1. 添加依赖

    在你的 pom.xmlbuild.gradle 文件中添加 Spring Boot Actuator 依赖。

    xml
    <!-- pom.xml -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    groovy
    // build.gradle
    implementation 'org.springframework.boot:spring-boot-starter-actuator'
  2. 创建度量

    使用 MeterRegistry 来注册自定义度量。你可以在任何地方注入 MeterRegistry 并使用它来注册度量。

    java
    @Component
    public class CustomMetrics {
    
        private final MeterRegistry registry;
    
        @Autowired
        public CustomMetrics(MeterRegistry registry) {
            this.registry = registry;
        }
    
        @PostConstruct
        public void init() {
            Counter counter = registry.counter("custom.requests");
            counter.increment(); // 每次请求增加计数器
        }
    }
  3. 使用度量

    你可以在需要的地方调用 increment() 方法来更新计数器。对于其他类型的度量(如 Gauge, Timer 等),可以使用相应的方法。