当前位置: 首页 > 知识库问答 >
问题:

Spring Cloud Sleuth:将traceId传播到其他Spring应用程序

佘俊茂
2023-03-14

我有一些spring服务可以提交一些AWS批处理作业。这是调用外部服务请求的简单spring批处理作业。并且我想通过将“org.springframework.cloud:spring-cloud-starter-sleuth”lib包含到classpath中,将在我的服务中生成的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);
   }
}
 x-b3-traceId=98519d97ce87553d
 dependencies {
    implementation('org.springframework.cloud:spring-cloud-starter-sleuth')
 }
INFO [-,,,] 15048 --- [           main] com.example.demo.DemoApplication         : Hello, world!

共有1个答案

长孙绍辉
2023-03-14

仅通过手动将具有相应值的请求头键“x-b3-traceid”(外部应用程序在提交目标Spring Boot应用程序时作为系统属性插入)解决了此问题。并在MDC中手动插入此键。例如,这个来自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);
    };
}
 类似资料: