首页 > 解决方案 > @SpringbootTest 中缺少 /actuator/prometheus

问题描述

我正在使用 springboot 2.4.0 并添加了以下依赖项以启用 prometheus 指标:

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

然后在我的 application.properties 我有以下属性

management.endpoints.web.exposure.include=*
management.metrics.enable.all=true

我正在尝试运行一个简单的集成测试,以查看我的自定义指标出现在 /actuator/prometheus 端点。代码下方

package com.example.demo;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.server.LocalServerPort;
import static io.restassured.RestAssured.given;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class IntegrationTest {

  @LocalServerPort
  private int port;

  private String baseUrl;

  @BeforeEach
  public void setup() {
      baseUrl = "http://localhost:" + port;
  }

  @Test
  public void metricsEndpoint() throws Exception {

    given().when().get(baseUrl + "/demo/actuator/prometheus")
            .then()
            .statusCode(200);
    }
}

我在这里得到的错误是

java.lang.AssertionError: 1 expectation failed.
Expected status code <200> but was <404>.

而如果我对 springboot 执行器提供的任何其他端点重复相同的请求,我会正确地得到响应,例如我尝试了 /actuator/health、/actuator/info、/actuator/metrics 等。

这只发生在使用 @Springboot 注释的集成测试期间,这很奇怪,因为如果我运行我的应用程序并使用邮递员向地址 localhost:8080/actuator/prometheus 发出请求,我会正确地得到响应。

就像在测试期间没有加载 prometheus 注册表一样。

任何人都可以帮忙吗?

提前致谢。

编辑:解决方案是 Johannes Klug 建议的解决方案。添加注释@AutoConfigureMetrics 解决了我的问题

标签: javametricsspring-boot-actuatorspring-boot-testspring-micrometer

解决方案


我遇到了同样的问题。在通过 spring-context ConditionEvaluator 进行一些跟踪后,我发现新引入的@ConditionalOnEnabledMetricsExport("prometheus")条件 onPrometheusMetricsExportAutoConfiguration阻止了端点加载。

这是由于https://github.com/spring-projects/spring-boot/pull/21658而导致的预期行为,并影响 spring-boot 2.4.x

修复:将 @AutoConfigureMetrics 添加到您的测试中

@AutoConfigureMetrics
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class IntegrationTest {

推荐阅读