RestClient 未传播 TraceID

问题描述 投票:0回答:1

我最近从 RestTemplate 切换到 RestClient,并在项目中使用 SpringBoot 3.2.7 和 Java 21。我注意到当 microservice1 调用 microservice2 时 TraceId 不会被传播。它不应该是开箱即用的还是需要一些调整?这是我的 RestClient。请指教。

 @Bean(name = "restClient1")
    public RestClient restClient() {
        return RestClient
                .builder()
                .baseUrl("http://localhost:9100/v3/rest")
                .defaultHeader("Content-Type", MediaType.APPLICATION_JSON_VALUE)
                .build();
    }

spring-boot trace rest-client
1个回答
0
投票

因此,如果您不使用任何外部依赖项进行跟踪,则应该自己实现此逻辑。 只是一个简单的示例,如何转发带有相关信息的标头:
首先,将拦截器添加到您的 RestClient

@Configuration
public class AppConfig {
    @Bean(name = "myLocalhostRestClient")
    public RestClient restClient() {
        return RestClient.builder()
            .baseUrl("http://localhost:8080")
            .requestInterceptor((request, body, execution) -> {
                var correlationId = MDC.get("X-Correlation-Id");
                request.getHeaders().add("X-Correlation-Id", correlationId);
                return execution.execute(request, body);
            })
            .build();
    }
}

你可以像这样使用它:

@RestController
public class Controller {
    private final RestClient localhostRestClient;
    public Controller(RestClient localhostRestClient) {
        this.localhostRestClient = localhostRestClient;
    }
    @GetMapping
    public String hello(@RequestHeader(name = "X-Correlation-ID", required = false) String correlationId) {
        if (!StringUtils.hasText(correlationId)) {
            System.out.println("this is a first request in a chain. generate correlation header by myself");
            correlationId = UUID.randomUUID().toString();
        }
        MDC.put("X-Correlation-Id", correlationId);
        var greetingResponse = localhostRestClient.get()
            .uri("/greeting")
            .retrieve()
            .body(String.class);
        return "Hello " + greetingResponse.toString();
    }
    @GetMapping("/greeting")
    public String greeting(@RequestHeader(name = "X-Correlation-ID") String correlationId) {
        System.out.println("Recieved correlation ID: " + correlationId);
        return "Some random Person";
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.