spring 千分尺跟踪traceId未进入下游

sdnqo3pr  于 2023-09-29  发布在  Spring
关注(0)|答案(1)|浏览(158)

假设我有两个微服务。尝试使用Micrometer时,traceId未遍历到下一个微服务。
我提供的购物车服务将调用产品服务的代码。
在购物车和产品服务中打印的traceId不同。
无法理解这个问题。

server.port=8081
spring.application.name=product_catalog
logging.level.org.springframework.web.servlet.DispatcherServlet=TRACE
management.tracing.sampling.probability=1.0
management.endpoints.web.exposure.include=*
logging.pattern.level=%5p [${spring.application.name:},%X{traceId:-},%X{spanId:-}]


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class ShoppingCartService {

@Autowired
RestTemplate restTemplate;
Logger logger = LoggerFactory.getLogger(ShoppingCartService.class);

@GetMapping("/cart")
public String addItem() {
    logger.info("add item - process started");
    final Product itemProduct = 
restTemplate.getForObject("http://localhost:8081/product",
            Product.class);
    System.out.println("itemProduct" + itemProduct);
    return "ok";
    }
}




     <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-aop</artifactId>
    </dependency>
    <dependency>
        <groupId>io.micrometer</groupId>
        <artifactId>micrometer-tracing-bridge-brave</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
blpfk2vs

blpfk2vs1#

迁移到Sping Boot 3后,您需要向RestTemplate添加拦截器。
这对我很有效。
将库添加到pom.xml

<dependency>
    <groupId>io.zipkin.brave</groupId>
    <artifactId>brave-instrumentation-spring-web</artifactId>
</dependency>

将TracingClientHttpRequestInterceptor添加到RestTemplate

import brave.Tracing;
import brave.http.HttpTracing;
import brave.spring.web.TracingClientHttpRequestInterceptor;
@Bean
public HttpTracing create(Tracing tracing) {
    return HttpTracing
        .newBuilder(tracing)
        .build();
}

@Bean
public RestTemplate restTemplate(HttpTracing httpTracing) {
    return new RestTemplateBuilder()           
            .interceptors(TracingClientHttpRequestInterceptor.create(httpTracing))
        .build();
}

希望这对你有帮助!

相关问题