我有一个带有spring-cloud-sleuth(Hoxton.SR3)的spring boot(2.2.5.RELEASE)项目,我想向一个包含头的控制器发送一个请求,并让这个头。
currentSpan.context().extra()
)我有一个定制的 TracingConfiguration
@Bean
public Tracing tracing(@Value("${spring.application.name}") String serviceName, TracingProperties tracingProperties,
CurrentTraceContext currentTraceContext) {
String profile = String.join(",", env.getActiveProfiles());
log.info("Enable tracing for service {}", serviceName + ":" + profile);
return Tracing.newBuilder()
.localServiceName(serviceName + ":" + profile)
.currentTraceContext(ThreadLocalCurrentTraceContext.newBuilder()
.addScopeDecorator(MDCScopeDecorator.create()) // puts trace IDs into logs
.build()
)
.sampler(Sampler.NEVER_SAMPLE)
.propagationFactory(
ExtraFieldPropagation.newFactoryBuilder(B3Propagation.FACTORY)
.addPrefixedFields(TracingConstant.BAGGAGE_HEADER_PREFIX, tracingProperties.getAllBaggageKeys())
.build())
.build();
}
当 tracingProperties.getAllBaggageKeys
返回从我的配置文件中读取的行李键列表。
我也在application.yml中定义了。
spring:
sleuth:
log:
slf4j:
whitelisted-mdc-keys:
- behalf-flow-id
- behalf-requested-time
- x-behalf-ach-file-name
- behalf-principal-id
- x-http-request-id
- behalf-principal
- requestid
baggage-keys:
- behalf-flow-id
- behalf-requested-time
- x-behalf-ach-file-name
- behalf-principal-id
- x-http-request-id
- behalf-principal
- requestid
当我调用(通过POSTMAN)服务控制器时, 头部的键是: baggage-behalf-requested-time
和价值 123456
我进去了 currentSpan.context().extra()
价值 baggage-behalf-requested-time
(即 123456
)
疑问
baggage-
框架不是应该自己处理吗?还是说当我用Spring本身发送请求时,它就会自己处理(即 RestTemplate
)?baggage-behalf-requested-time
头部?你有你的自定义跟踪机制,这就是为什么你需要照顾到所有的人。baggage-
前缀等。如果你查看Sleuth的2.2.2.2.RELEASE,你会发现我们自己确实给这些字段加了前缀。https:/github.comspring-cloud-sleuthblobv2.2.2.RELEASEspring-cloud-sleuth-coresrcmainjavaorgspringframeworkcloudsleuthautoconfigTraceAutoConfiguration.java#L168-L174。 然后,它们也会被填充到MDC(https:/github.comspring-cloud-sleuthblobv2.2.2.RELEASEspring-cloud-sleuth-coresrcmainjavaorgspringframeworkcloudsleuthlogSlf4jScopeDecorator.java。),但不包括 baggage-
前缀。在最新版本(2.2.3.RELEAE)中,代码得到了重构,但概念上是相似的。
只要做
public String someMethod(HttpServletRequest request, HttpServletResponse httprespons)
{
MDC.put(request.getHeader("header_name"););
}
通过HttpServletRequest,HttpServletResponse作为参数。
你可以编写customeFilter来拦截每个请求,并将请求中的数据放到MDC中。
@Component
public class CustomFilter implements Filter {
@Override
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
final String correlationId = getCorrelationIdFromHeader(req);
MDC.put(HttpConstants.CORRELATION_ID_HEADER_NAME, correlationId);
chain.doFilter(req, res);
}
}