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



我正在使用侦探与CompletableFuture.handle。例子:

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

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

注:我不能控制apnsClient.sendNotification如何管理线程(因为那是来自Pushy),所以没有办法使用像LazyTraceExecutor这样的东西。

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

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

最新更新