Spring Cloud 异步traceId为空解决

Spring Cloud 异步流程traceId和spanId为空,如EventBus或MQ等异步操作的traceId和spanId为空,需要手动生成traceId和spanId

@Slf4j
public abstract class MyJob implements SimpleJob {

    @Override
    public final void execute(ShardingContext shardingContext) {

        log.info(String.format("任务总片数: %s, 当前分片项: %s, 分片参数: %s", shardingContext.getShardingTotalCount(),
                shardingContext.getShardingItem(), shardingContext.getShardingParameter()));

        TraceHelper.newTrace();

    }
}

@Slf4j
@Component
public class TraceHelper {

    private static Tracer tracer;
    private static Environment env;

    @Autowired
    public void setTracer(Tracer tracer) {
        TraceHelper.tracer = tracer;
    }

    @Autowired
    public void setEnv(Environment env) {
        TraceHelper.env = env;
    }

    public static void newTrace() {
        tracer.startScopedSpanWithParent(getApplicationName(), tracer.newTrace().context());
    }

    private static boolean isNumber(String str) {
        return str.matches("-?\\d+");
    }

    private static String getApplicationName() {
        return env.getProperty("spring.application.name", "");
    }

    public static long getTraceId() {
        return tracer.currentSpan().context().traceId();
    }

    public static long getSpanId() {
        return tracer.currentSpan().context().spanId();
    }

    public static long getParentId() {
        return tracer.currentSpan().context().parentId();
    }

    public static boolean getSampled() {
        return tracer.currentSpan().context().sampled();
    }

    public static String getTraceIdString() {
        return tracer.currentSpan().context().traceIdString();
    }

    public static String getSpanIdString() {
        return tracer.currentSpan().context().spanIdString();
    }
}

版权声明:
作者:Joe.Ye
链接:https://www.appblog.cn/index.php/2023/04/01/spring-cloud-asynchronous-traceid-empty/
来源:APP全栈技术分享
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
打赏
海报
Spring Cloud 异步traceId为空解决
Spring Cloud 异步流程traceId和spanId为空,如EventBus或MQ等异步操作的traceId和spanId为空,需要手动生成traceId和spanId @Slf4j public abstract class My……
<<上一篇
下一篇>>
文章目录
关闭
目 录