如何将 traceId 从 gRPC 的上下文传递到另一个 thread/threadPool?

How to pass on a traceId from gRPC's context to another thread/threadPool?

我正在使用 grpc-java 并有 3 个服务,A、B 和 C。我调用服务 A,然后服务 A 调用 B 和 C。我在调用 B 和 C 时使用 Hystrix . C 依次生成另一个线程来调用另一个服务。

我有传递 traceId 的 ClientInterceptors 和 ServerInterceptors。只要它是 gRPC 工作线程,我就可以在 Context 和日志中看到 traceIds,但是当调用移动到另一个线程 - RxIoScheduler 线程或 Hystrix 线程时,它们就会丢失。如何在不同线程上的请求之间以及不同执行程序服务和线程池之间传递 traceId?

虽然可以以细粒度的方式传播(如 executor.execute(Context.current().wrap(runnable))),但您应该尝试将 Context 传播集成到跨线程工作传输中。对于许多应用程序,创建后就像 wrapping the "main" executor 一样简单:

executor = Context.currentContextExecutor(executor);
// executor now auto-propagates

在您的应用程序开始时执行一次,然后您基本上就不再担心传播问题了。

但应用程序会有所不同。例如,直接创建 Thread 的应用程序可能应该创建一个 ThreadFactory 将调用线程的 Context 传播到 Thread:

class PropagatingThreadFactory implements ThreadFactory {
  private final ThreadFactory delegate;

  public PropagatingThreadFactory(ThreadFactory d) {delegate = d;}

  @Override public Thread newThread(Runnable r) {
    return delegate.newThread(Context.current().wrap(r));
  }
}