Gateway中Sleuth的traceId为空

一、问题背景

SpringCloud版本为2020.0.4,SpringBoot版本为2.5.6,网关采用Spring Cloud Gateway,响应日志没有traceId和spanId。

Gateway中Sleuth的traceId为空

二、浅层缘由分析

Spring Cloud Gateway基于WebFlux框架实现,WebFlux底层使用Netty(Reactor模式)。
Reactor模式下,官方文档鼓励采用MANUAL模式:
https://docs.spring.io/spring-cloud-sleuth/docs/3.0.3/reference/html/integrations.html#sleuth-reactor-integration

Gateway中Sleuth的traceId为空

github issues:

Gateway中Sleuth的traceId为空

核心是说,2020.0.0版本后来为了提升性能,webflux+sleuth的链路追踪默认为Manual模式,Reactor中不会传递跟踪号,需要手动获取。
(webmvc+sleuth不受影响,链路追踪模式默认为ON_EACH)

三、解决方案

既然为Manual模式,那可以通过WebFluxSleuthOperators.withSpanInScope()手动获取。

import org.springframework.cloud.sleuth.CurrentTraceContext;
import org.springframework.cloud.sleuth.Tracer;
import org.springframework.cloud.sleuth.instrument.web.WebFluxSleuthOperators;

public class DefaultFilter implements GlobalFilter, Ordered {

    @Autowired
    private Tracer tracer;
    @Autowired
    private CurrentTraceContext currentTraceContext;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 打印日志
        WebFluxSleuthOperators.withSpanInScope(tracer, currentTraceContext, exchange, () -> log.info("打印日志"));
    }
}

© 版权声明
THE END
如果内容对您有所帮助,就支持一下吧!
点赞0 分享
JoyceRegina的头像 - 鹿快
评论 抢沙发

请登录后发表评论

    暂无评论内容