Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to pass information between threads using Sleuth

Shulou Source: shulou.com Published: 2022-06-02 10:37:07 10月03日 Update

It is believed that many inexperienced people have no idea about how to use Sleuth to transmit information between threads. Therefore, this article summarizes the causes and solutions of the problem. Through this article, I hope you can solve this problem.

Public class LazyTraceExecutor implements java.util.concurrent.Executor {private static final Log log = LogFactory.getLog (MethodHandles.lookup (). LookupClass ()); private Tracer tracer; private final BeanFactory beanFactory; private final Executor delegate; private TraceKeys traceKeys; private SpanNamer spanNamer; public LazyTraceExecutor (BeanFactory beanFactory, Executor delegate) {this.beanFactory = beanFactory; this.delegate = delegate } @ Override public void execute (Runnable command) {if (this.tracer = = null) {try {this.tracer = this.beanFactory.getBean (Tracer.class);} catch (NoSuchBeanDefinitionException e) {this.delegate.execute (command); return } this.delegate.execute (new SpanContinuingTraceRunnable (this.tracer, traceKeys (), spanNamer (), command);}}

Mode of use

@ Configurationpublic class MyConfiguration {@ Autowired BeanFactory beanFactory; @ Bean public Executor executor () {ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor (7); executor.setMaxPoolSize (42); executor.setQueueCapacity (11); executor.setThreadNamePrefix ("MyExecutor-"); / / DON'T FORGET TO INITIALIZE executor.initialize (); return new LazyTraceExecutor (this.beanFactory, executor);}}

So it's not surprising that it can pass traceId between threads, because it basically requires you to use its multithreading tool.

4. Can the child thread get the parent thread information? 4. 1 can: InheritableThreadLocal

Generally speaking, we use ThreaLocal for one copy per thread. However, if you want both the thread and its child threads to be able to read this copy, you can use InheritableThreadLocal.

The usage is simple, Demo:

Private static final ThreadLocal sessionInfoHolder1 = new ThreadLocal (); private static final ThreadLocal sessionInfoHolder2 = new InheritableThreadLocal (); after reading the above, have you mastered how to use Sleuth to transfer information between threads? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!

Tags: Between threads information content copies methods more problems strangeness helplessness for this generally speaking the reason that is tools skills ways fundamentally an article Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno macOS Xiaomi NVidia OPPO Reno Linux