我有一些 Spring 服务可以提交一些 AWS 批处理作业。这是一个简单的 spring 批处理作业,它调用外部服务的请求。我想通过将“org.springframework.cloud:spring-cloud-starter-sleuth”lib包含到类路径中来传播在我的服务中生成的traceId到此作业,并将“TraceRestTemplateInterceptor”拦截器添加到使用此traceId初始化的外部请求。
我怎样才能做到这一点?我如何初始化拦截器,它将从应用程序参数、环境、属性中放入现有的traceId? 或者可能需要创建一些配置 bean?
更新:
简化示例:
@SpringBootApplication
public class DemoApplication implements CommandLineRunner {
Logger logger = LoggerFactory.getLogger(DemoApplication.class);
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
//@Autowired
//RestTemplate restTemplate;
@Override
public void run(String... args) {
logger.info("Hello, world!");
//restTemplate.getForObject("some_url", String.class);
}
}
文件application.properties:
x-b3-traceId=98519d97ce87553d
文件build.gradle:
dependencies {
implementation('org.springframework.cloud:spring-cloud-starter-sleuth')
}
输出:
INFO [-,,,] 15048 --- [ main] com.example.demo.DemoApplication : Hello, world!
首先,我想在这里看到在application.properties中初始化的traceId。其次,当取消注释resttemplate子句时,此traceId传播到请求中。
可能吗?
最佳答案
只能通过手动将相应值放入请求 header 键“X-B3-TRACEID”来解决此问题,该值是在提交目标 Spring Boot 应用程序时由外部应用程序作为系统属性插入的。并在MDC中手动插入此 key 。例如,来自 Spring Boot 应用程序的此片段必须获取 TraceId 并传播:
@Bean
public void setTraceIdToMDC(@Value("${x.b3.traceid}") String traceId) {
MDC.put("x-b3-traceId", traceId);
}
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
@Bean
public CommandLineRunner commandLineRunnerer(RestTemplate restTemplate, @Value("${x.b3.traceid}") String traceId) {
return args -> {
MultiValueMap<String, String> header = new LinkedMultiValueMap<>();
header.add("X-B3-TRACEID", traceId);
HttpEntity httpEntity = new HttpEntity(header);
logger.info("Execute some request"); //<-- prints expected traceId
restTemplate.exchange("some_url", HttpMethod.GET, httpEntity, String.class);
};
}
关于java - Spring Cloud 侦探 : Propagate traceId to other spring application,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53862629/