Spring Boot 3中如何实现微服务间Key传递?原Sleuth方案已失效
Spring Boot 3 实现微服务间自定义Key传递(替代Spring Sleuth)
Spring Boot 3 已移除spring-boot-starter-sleuth,官方推荐使用Micrometer Tracing作为分布式追踪方案,实现自定义Key的跨服务传递可以按以下步骤操作:
1. 引入依赖
首先添加Micrometer Tracing及对应桥接包(以常用的Brave桥接为例,适配Zipkin生态):
<!-- Micrometer Tracing核心依赖 --> <dependency> <groupId>io.micrometer</groupId> <artifactId>micrometer-tracing</artifactId> </dependency> <!-- Brave桥接包,负责实际的追踪逻辑实现 --> <dependency> <groupId>io.micrometer</groupId> <artifactId>micrometer-tracing-bridge-brave</artifactId> </dependency> <!-- 若使用Zipkin做追踪可视化,添加此依赖 --> <dependency> <groupId>io.zipkin.reporter2</groupId> <artifactId>zipkin-reporter-brave</artifactId> </dependency>
2. 配置自定义传播Key
替代原Sleuth的spring.sleuth.propagation-keys,在配置文件中添加以下配置即可指定要传播的自定义Key:
management: tracing: propagation: fields: my_key # 单个Key直接填写,多个用逗号分隔
3. 自定义传播逻辑(可选)
如果需要更灵活的提取/注入逻辑(比如自定义请求头名称映射),可以通过配置类扩展Brave的传播工厂:
import brave.propagation.Propagation; import brave.propagation.TraceContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class CustomTracingConfig { @Bean public Propagation.Factory propagationFactory() { // 自定义要传播的字段集合,支持多个Key return Propagation.Factory.create( Propagation.KeyFactory.INSTANCE, TraceContext.DEFAULT, "my_key", "another_custom_key" ); } }
注意事项
- 上下游微服务都需要配置相同的传播字段,才能保证Key在跨服务调用时正常传递
- 若使用OpenTelemetry作为桥接实现,
management.tracing.propagation.fields配置同样生效,也可通过OpenTelemetry的TextMapPropagator实现自定义逻辑
内容的提问来源于stack exchange,提问作者Hiluminatu l
相关产品推荐
相关产品推荐

