Spring Boot Sping Boot 3.0.2带千分尺的微服务,子进程获得与父进程不同的跟踪ID

5cg8jx4n  于 2023-03-02  发布在  Spring
关注(0)|答案(1)|浏览(169)

我有一个使用webclient调用另一个微服务(子服务)的父服务。

public Mono<Product> productFromIntegrator() {

        String url = "http://localhost:8282/product";

    return Mono.deferContextual(contextView -> {
        try (ContextSnapshot.Scope scope = ContextSnapshot.setThreadLocalsFrom(contextView,
                ObservationThreadLocalAccessor.KEY)) {
            LOG.info("<ACCEPTANCE_TEST> <TRACE:{}> Hello from producer", tracer.currentSpan().context().traceId());
            LOG.info("Service Called");
            return webClient.get().uri(url)
                    .retrieve().bodyToMono(Product.class).log(LOG.getName(), Level.FINE)
                    .onErrorMap(WebClientException.class, ex -> {
                        LOG.warn("Error retrieving Product");
                        return ex;
                    });
        }
    });
}

来自子级的RestController:

@Autowired
private final Service service;
private final Tracer tracer;

public Controller(Service service, Tracer tracer) {
    this.service = service;
    this.tracer = tracer;
}

@GetMapping(value = "/product")
public Mono<Product> getProduct() {

    return Mono.deferContextual(contextView -> {
        try (ContextSnapshot.Scope scope = ContextSnapshot.setThreadLocalsFrom(contextView,
                ObservationThreadLocalAccessor.KEY)) {
            LOG.info("<ACCEPTANCE_TEST> <TRACE:{}> Hello from producer", tracer.currentSpan().context().traceId());
            LOG.info("Service Called");
            return this.service.getProduct();
        }
    });
}

子级未从父级获取TraceId,它正在创建新的观察对象。关于如何将TraceId从父级传播到子级,有何建议/示例?

z5btuh9x

z5btuh9x1#

找到了:How to get trace-id in spring-cloud-gateway using micrometer-brave
在psvm中添加挂钩。

import reactor.core.publisher.Hooks;

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        Hooks.enableContextLossTracking();
        SpringApplication.run(DemoApplication.class, args);
    }
}

相关问题