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

Spring Boot+Kafka集成OpenTelemetry链路追踪配置问题求助

解决方案:配置OpenTelemetry的B3 Propagator

问题根源

你遇到的NoopTextMapPropagator是OpenTelemetry的默认行为——当未显式配置传播器时,它会使用空实现,不会注入任何追踪头。要生成B3格式的追踪头,需要显式启用OpenTelemetry的B3传播器,并确保其正确初始化。

步骤1:添加B3 Propagator依赖

首先需要引入OpenTelemetry的B3传播器依赖,在你的构建文件中添加:

implementation("io.opentelemetry:opentelemetry-propagators-b3")

步骤2:配置B3 Propagator

有两种方式可以配置,根据你的偏好选择:

方式一:自动配置(推荐)

如果你已经引入了opentelemetry-sdk-extension-autoconfigure依赖,可以通过配置文件直接指定传播器。在application.yml中添加:

otel:
  propagators: b3

注:该配置会自动初始化OpenTelemetry SDK并启用B3传播器,无需手动编写Bean。

方式二:手动Bean配置

如果需要更精细的控制,可以手动创建OpenTelemetry的Bean并指定B3传播器:

@Configuration
class OpenTelemetryConfig {
    @Bean
    fun openTelemetry(): OpenTelemetry {
        val b3Propagator = B3Propagator.getDefault()
        return OpenTelemetrySdk.builder()
            .setPropagators(ContextPropagators.create(b3Propagator))
            .buildAndRegisterGlobal()
    }
}

步骤3:与Spring Cloud Sleuth的兼容注意事项

如果需要保留Spring Cloud Sleuth,需要注意:

  • Sleuth默认使用B3格式,但它的上下文和OpenTelemetry的上下文是独立的。若要让两者协同工作,可以配置Sleuth使用OpenTelemetry作为底层实现,添加以下依赖:
    implementation("org.springframework.cloud:spring-cloud-sleuth-otel")
    
    此时无需手动配置OpenTelemetry的传播器,Sleuth会自动处理B3头的注入。

验证配置

重启应用后,发送Kafka消息时,消息头中应该会包含b3字段,格式为traceId-spanId-sampled(例如:463ac35c9f6413ad48485a3953bb6124-0011223344556677-1)。

内容的提问来源于stack exchange,提问作者Тим

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 05:22:32