1. TraceId
发现问题
用于跟踪一个请求的id, 一般由apigateway生成,在下层服务中获取:
import org.springframework.cloud.sleuth.Tracer;
@Autowired
private Tracer tracer;
StringId = tracer.getCurrentSpan().traceIdString();
但在线程池中,主线程的traceId默认不会传递给子线程,
因此子线程中 tracer.getCurrentSpan()
会是null,从而抛出空指针
2.解决问题
我们只需要在子线程中传递主线程的span
代码实现
1. 在主线程中获取span
Span span= tracer.getCurrentSpan();
2.传递给子线程
Future<Object> ngFuture = executor.submit(new Callable<Object>() {
@SneakyThrows
public Object call() {
return wrap(() -> ngInvoke(migrator, joinPoint), traceId, context);
}}); 或
return wrap(joinPoint::proceed, traceId, context);
}});
private Object wrap(ExceptionSupplier.ThrowingSupplier<Object> supplier, Span span) throws Throwable {
Span span = tracer.createSpan("sub", span);
//创建一个子span,并将父span传递进去
try {
return supplier.get();
} finally {
if (span != null) {
span.stop();
}
//结束该span
}
}
在子线程中使用tracer.getCurrentSpan().traceIdtoString()获取
warp方法是在子线程中执行的