Spring Boot 3.1下Micrometer Tracing无法传递至下游(无RestTemplate)求助
解决Micrometer Tracing TraceId不传递到下游的方案
由于你使用OpenAPI Generator生成的客户端、未依赖RestTemplate,可通过自定义拦截器注入TraceId相关请求头,同时兼容Spring Boot 3.1的Micrometer Tracing与下游2.7.x的Sleuth格式,具体步骤如下:
1. 自定义OpenAPI请求拦截器
利用OpenAPI Generator客户端的RequestInterceptor扩展点,在请求发送前注入TraceId相关头信息:
import io.micrometer.tracing.Tracer; import org.openapitools.client.api.ApiClient; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class OpenApiClientConfig { private final Tracer tracer; public OpenApiClientConfig(Tracer tracer) { this.tracer = tracer; } @Bean public ApiClient apiClient() { ApiClient apiClient = new ApiClient(); // 添加自定义请求拦截器 apiClient.addRequestInterceptor(request -> { var currentSpan = tracer.currentSpan(); if (currentSpan != null) { var traceContext = currentSpan.context(); // 注入Sleuth兼容的B3格式头信息 request.header("X-B3-TraceId", traceContext.traceId()); request.header("X-B3-SpanId", traceContext.spanId()); request.header("X-B3-Sampled", "1"); } }); return apiClient; } }
2. 确认Micrometer Tracing依赖配置
Spring Boot 3.1已用Micrometer Tracing替代Sleuth,需引入正确的桥接依赖:
<dependency> <groupId>io.micrometer</groupId> <artifactId>micrometer-tracing-bridge-brave</artifactId> </dependency> <dependency> <groupId>io.zipkin.reporter2</groupId> <artifactId>zipkin-reporter-brave</artifactId> </dependency>
3. 配置Trace传播格式
下游2.7.x依赖Sleuth的B3格式,需在application.yml中指定传播类型:
management: tracing: propagation: type: B3
4. 验证生效
启动服务后,调用OpenAPI生成的客户端接口,检查请求头是否包含X-B3-TraceId、X-B3-SpanId字段,同时确认下游服务日志能正确接收并打印TraceId。
内容的提问来源于stack exchange,提问作者Rishy Rane
相关产品推荐
相关产品推荐

