在 Spring Cloud Sleuth 中保持 CompletableFuture 的跟踪/跨度

fzy*_*cjy 2 java spring spring-cloud completable-future spring-cloud-sleuth

我正在将 Sleuth 与CompletableFuture.handle. 例子:

log.info("first");
apnsClient.sendNotification(...).handle((response, cause) -> {
     log.info("second");
});
Run Code Online (Sandbox Code Playgroud)

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

PS 我无法控制如何apnsClient.sendNotification管理线程(因为它来自Pushy),因此无法使用LazyTraceExecutor之类的东西。

Mar*_*zak 6

您可以做的是检索之前的跨度(例如通过tracer.currentSpan()log.info("first"),将跨度传递给 lambdalog.info("second")并通过手动继续跟踪tracer.withSpanInScope(span)。它看起来像这样:

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