在 Spring Cloud Sleuth 中保持 trace/span 跨越 CompletableFuture

Keep trace/span across CompletableFuture in Spring Cloud Sleuth

我在 CompletableFuture.handle 中使用 Sleuth。示例:

log.info("first");
apnsClient.sendNotification(...).handle((response, cause) -> {
     log.info("second");
});

我希望 second 日志与 first 日志具有相同的跟踪 ID。然而,事实并非如此。因此我想知道该怎么办?谢谢!

P.S。我无法控制 apnsClient.sendNotification 如何管理线程(因为那来自 Pushy), so there is no way to use things like LazyTraceExecutor.

你可以做的是在 log.info("first") 之前检索跨度(例如通过 tracer.currentSpan()),使用 log.info("second") 将跨度传递给 lambda 并通过 [=14 手动继续跟踪=].它会像这样:

Span span = tracer.currentSpan();
log.info("first");
apnsClient.sendNotification(...).handle((response, cause) -> {
     try (SpanInScope ws = tracer.withSpanInScope(span)) {
         log.info("second");
     }
});