您好,登錄后才能下訂單哦!
使用Sleuth怎么在線程之間傳遞信息,相信很多沒有經驗的人對此束手無策,為此本文總結了問題出現的原因和解決方法,通過這篇文章希望你能解決這個問題。
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)); } }
使用方式
@Configuration public class MyConfiguration { @Autowired BeanFactory beanFactory; @Bean public Executor executor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); // CUSTOMIZE HERE executor.setCorePoolSize(7); executor.setMaxPoolSize(42); executor.setQueueCapacity(11); executor.setThreadNamePrefix("MyExecutor-"); // DON'T FORGET TO INITIALIZE executor.initialize(); return new LazyTraceExecutor(this.beanFactory, executor); } }
所以它能在線程之間傳遞traceId并不稀奇,因為它根本就是要你使用它的多線程工具。
一般來說,每個線程一個副本,我們都是用ThreaLocal。可是,如果你想要該線程和它的子線程都能讀這個副本,那就可以用InheritableThreadLocal了。
用法很簡單Demo:
private static final ThreadLocal<String> sessionInfoHolder1 = new ThreadLocal<String>(); private static final ThreadLocal<String> sessionInfoHolder2 = new InheritableThreadLocal<String>();
看完上述內容,你們掌握使用Sleuth怎么在線程之間傳遞信息的方法了嗎?如果還想學到更多技能或想了解更多相關內容,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。