Spring Cloud 异步traceId为空解决

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

1
2
3
4
5
6
7
8
9
10
11
12
13
@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();

}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
@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();
}
}

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2021 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :