You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过MicroProfile以编程方式重置Quarkus应用的所有指标?

解决方案

方法一:在测试的tearDown阶段直接重置指标

利用Quarkus依赖注入能力,在测试类中注入MicroProfile的MetricRegistry,在测试清理阶段执行指标清除逻辑。

实现步骤:

  1. 注入应用级MetricRegistry(指定类型避免影响Quarkus内置基础指标)
  2. 在JUnit的@AfterEach(对应JUnit 4的tearDown)方法中执行清除操作
import org.eclipse.microprofile.metrics.MetricRegistry;
import org.eclipse.microprofile.metrics.annotation.RegistryType;
import jakarta.inject.Inject;
import org.junit.jupiter.api.AfterEach;
import io.quarkus.test.junit.QuarkusTest;

@QuarkusTest
public class CustomMetricsTest {

    // 仅注入应用自定义指标所在的注册表
    @Inject
    @RegistryType(type = RegistryType.Type.APPLICATION)
    MetricRegistry appMetricRegistry;

    @AfterEach
    void tearDown() {
        // 一键清除所有应用自定义指标
        appMetricRegistry.clear();

        // 若需精准过滤特定前缀的自定义指标(比如前缀为"app."),可替换为:
        // Set<String> customMetricNames = new HashSet<>(appMetricRegistry.getMetrics().keySet());
        // customMetricNames.stream()
        //     .filter(name -> name.startsWith("app."))
        //     .forEach(appMetricRegistry::remove);
    }
}

注意:如果使用的MicroProfile Metrics版本低于2.0,MetricRegistry可能没有clear()方法,此时需通过遍历并逐个移除指标(如上注释代码)。

方法二:创建仅测试环境可用的REST重置接口

通过Quarkus的@IfBuildProfile注解创建仅在test环境加载的REST接口,用于外部触发指标重置。

实现步骤:

  1. 编写带环境限定的REST资源类
  2. 注入MetricRegistry并提供重置接口
  3. 在测试中调用该接口完成清理

1. 编写测试专用REST资源

import org.eclipse.microprofile.metrics.MetricRegistry;
import org.eclipse.microprofile.metrics.annotation.RegistryType;
import jakarta.inject.Inject;
import jakarta.ws.rs.DELETE;
import jakarta.ws.rs.Path;
import io.quarkus.arc.profile.IfBuildProfile;

@Path("/test/metrics")
@IfBuildProfile("test") // 仅在test构建环境下激活该类
public class TestMetricsResetResource {

    @Inject
    @RegistryType(type = RegistryType.Type.APPLICATION)
    MetricRegistry appMetricRegistry;

    @DELETE
    @Path("/reset")
    public void resetCustomMetrics() {
        appMetricRegistry.clear();
        // 或使用自定义过滤逻辑移除指定指标
    }
}

2. 配置测试环境接口权限

在src/test/resources/application-test.properties中添加配置,允许无认证访问该测试接口:

# 开放测试指标重置接口的访问权限
quarkus.http.auth.permission.test-metrics-reset.paths=/test/metrics/reset
quarkus.http.auth.permission.test-metrics-reset.policy=permit

3. 在测试中调用重置接口

import static io.restassured.RestAssured.given;
import org.junit.jupiter.api.AfterEach;
import io.quarkus.test.junit.QuarkusTest;

@QuarkusTest
public class BusinessServiceTest {

    @AfterEach
    void tearDown() {
        // 调用测试接口完成指标重置
        given()
            .when()
            .delete("/test/metrics/reset")
            .then()
            .statusCode(204);
    }
}

内容的提问来源于stack exchange,提问作者João Pedro Schmitt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 04:53:17