如何将traceId从gRPC的上下文传递到另一个线程/threadPool? [英] How to pass on a traceId from gRPC's context to another thread/threadPool?

查看:180
本文介绍了如何将traceId从gRPC的上下文传递到另一个线程/threadPool?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用grpc-java并具有3个服务,即A,B和C.我先调用service A,然后服务A调用B和C.我在对B和C的调用中使用Hystrix.C又产生了另一个线程调用另一个服务.

I am using grpc-java and have 3 services, A, B and C. I call service A and then service A calls B and C. I am using Hystrix in the calls to B and C. C in turn spawns another thread to call another service.

我有ClientInterceptor和ServerInterceptor,它们围绕traceId传递.只要它是gRPC工作线程,我就可以在Context中看到traceIds并进行记录,但是当调用移至另一个线程-RxIoScheduler线程或Hystrix线程时,它们会丢失.如何在不同线程上的请求之间以及不同执行程序服务和线程池之间传递traceId?

I have ClientInterceptors and ServerInterceptors which passes around the traceId. I can see the traceIds in the Context and logs as long as it is a gRPC worker thread but lose them when the call moves to another thread - RxIoScheduler thread or Hystrix thread. How do I pass the traceId around between requests on different threads and between different executor service and thread pools?

推荐答案

虽然可以以细粒度的方式传播(例如 executor.execute(Context.current().wrap(runnable)))),则应尝试将 Context 传播集成到跨线程工作传输中.对于许多应用程序,它就像在创建主要"执行程序后立即对其进行包装:

While it is possible to propagate in a fine-grained way (like executor.execute(Context.current().wrap(runnable))), you should try to integrate Context propagation into cross-thread work transfer. For many applications, that'd be as simple as wrapping the "main" executor as soon as it is created:

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

在您的应用程序开始执行一次操作,然后您就不再需要担心传播了.

Do that once at the beginning of your application and then you mostly stop worrying about propagation.

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

But applications will vary. For example, applications that create Threads directly should probably make a ThreadFactory that propagates the calling thread's Context to the 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));
  }
}

这篇关于如何将traceId从gRPC的上下文传递到另一个线程/threadPool?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆