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

Java中OpenTelemetry ContextStorage配置:测试无需Vert.x的解决方案

解决Vert.x OpenTelemetry上下文存储导致无Vert.x测试失败的问题

以下几种方案可以帮你无需在每个测试类重复设置系统属性,直接使用默认的ThreadLocalContextStorage:

1. 通过Maven测试插件全局配置系统属性

在项目pom.xml中配置Surefire/Failsafe插件,全局添加强制使用默认上下文提供器的系统属性,所有测试用例会自动继承该配置:

<build>
  <plugins>
    <!-- 单元测试配置 -->
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-surefire-plugin</artifactId>
      <configuration>
        <systemPropertyVariables>
          <otel.context.storage.provider>io.opentelemetry.context.ThreadLocalContextStorageProvider</otel.context.storage.provider>
        </systemPropertyVariables>
      </configuration>
    </plugin>
    <!-- 集成测试配置(如有) -->
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-failsafe-plugin</artifactId>
      <configuration>
        <systemPropertyVariables>
          <otel.context.storage.provider>io.opentelemetry.context.ThreadLocalContextStorageProvider</otel.context.storage.provider>
        </systemPropertyVariables>
      </configuration>
    </plugin>
  </plugins>
</build>

2. 通过SPI机制覆盖上下文提供器

OpenTelemetry依靠SPI加载ContextStorageProvider,你可以在测试资源中创建配置文件强制指定默认实现:

  • 在src/test/resources下创建路径META-INF/services/io.opentelemetry.context.ContextStorageProvider
  • 文件内仅写入默认实现的全类名:
io.opentelemetry.context.ThreadLocalContextStorageProvider

测试运行时,SPI会优先读取该配置,替代vert.x的上下文存储实现。

3. 测试基类中手动设置上下文存储

创建一个所有测试类继承的基类,在初始化阶段手动指定上下文存储:

import io.opentelemetry.context.ContextStorage;
import io.opentelemetry.context.ThreadLocalContextStorage;
import org.junit.jupiter.api.BeforeAll;

public class BaseTest {
    @BeforeAll
    static void setupOpenTelemetryContext() {
        // 确保在任何OpenTelemetry操作前执行此设置
        ContextStorage.set(new ThreadLocalContextStorage());
    }
}

所有无需Vert.x的测试类继承该基类即可生效。

关于自定义Provider未加载的说明

你之前尝试的自定义Provider未被加载,通常是以下原因导致:

  • 自定义Provider的全类名未正确写入META-INF/services/io.opentelemetry.context.ContextStorageProvider文件
  • 配置文件放在了src/main/resources而非src/test/resources,测试时未被读取
  • 类加载顺序问题,vert.x的Provider先被注册,自定义Provider未被优先选中

方案2通过SPI配置直接覆盖加载逻辑,可解决该问题。

内容的提问来源于stack exchange,提问作者mihZR

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 15:25:23