如何在 Spring-boot 中创建指标?

How to create a metric in Spring-boot?

如何在SpringBoot2.1中创建metric4.RELEASE?

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

可以使用千分尺:

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>io.micrometer</groupId>
            <artifactId>micrometer-registry-prometheus</artifactId>
        </dependency>

这将为您提供终点:/actuator/prometheus

如果您正在使用 spring-boot-starter-actuator,将创建类型为 MeterRegistry 的 bean。自动装配后,这允许您创建多个指标,例如计数器、仪表和指标。其中每一个都有一个流畅的构建器,您可以使用它来设置它们,例如:

计数器

A Counter 可用于简单的递增指标,例如调用方法的次数。

Counter customCounter = Counter
    .builder("my.custom.metric.counter")
    .register(meterRegistry);

通过使用 customCounter.increment() 您可以增加该值。

仪表

另一方面,

A Gauge 是应该直接测量的 dynamic/live 值。一个例子是连接池的大小:

 Gauge
      .builder("my.custom.metric.gauge", () -> connectionPool.size())
      .register(meterRegistry);

构建器允许您传递一个 Supplier 来测量您想要的任何东西。

计时器

顾名思义,这可以用来衡量做某事所花费的时间,例如:

Timer customTimer = Timer
     .builder("my.custom.metric.timer")
     .register(meterRegistry);

通过使用 customTimer.record(() -> myMethod()),您可以添加有关调用 myMethod().

所需时间的指标

您应该能够在 运行 应用程序时访问这些指标。如果你想通过 HTTP 查看它们,你可以像这样启用指标端点:

management.endpoints.web.exposure.include=metrics # Enable metrics endpoint

之后,您应该可以访问 http://localhost:8080/actuator to see the list of enabled endpoints, which should contain http://localhost:8080/actuator/metrics

此 API 应该 return 可用指标列表,可以通过 http://localhost:8080/actuator/metrics/my.custom.metric.counter.

访问