spring 微米跟踪中的Sping Boot 3上下文传播

bqucvtff  于 2023-02-18  发布在  Spring
关注(0)|答案(1)|浏览(174)

Sping Boot 3更改了跟踪中的上下文传播。https://github.com/micrometer-metrics/tracing/wiki/Spring-Cloud-Sleuth-3.1-Migration-Guide#async-instrumentation
他们现在提供了这个问题的库。我想我不太明白它是如何工作的。我已经创建了一个任务执行器作为指南。

@Bean(name = "taskExecutor")
    ThreadPoolTaskExecutor threadPoolTaskScheduler() {
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor() {
            @Override
            protected ExecutorService initializeExecutor(ThreadFactory threadFactory, RejectedExecutionHandler rejectedExecutionHandler) {
                ExecutorService executorService = super.initializeExecutor(threadFactory, rejectedExecutionHandler);
                return ContextExecutorService.wrap(executorService, ContextSnapshot::captureAll);
            }
        };
        threadPoolTaskExecutor.initialize();
        return threadPoolTaskExecutor;
    }

我把@Async标记为:

@Async("taskExecutor")
    public void run() {
        // invoke some service
    }

但上下文不会传播到taskExecutor线程中的子上下文。

gajydyqb

gajydyqb1#

我也遇到了同样的问题。请将此代码添加到配置中,一切都按预期工作。

@Configuration(proxyBeanMethods = false)
  static class AsyncConfig implements AsyncConfigurer, WebMvcConfigurer {

    @Override
    public Executor getAsyncExecutor() {
      return ContextExecutorService.wrap(Executors.newCachedThreadPool(), ContextSnapshot::captureAll);
    }

    @Override
    public void configureAsyncSupport(AsyncSupportConfigurer configurer) {
      configurer.setTaskExecutor(new SimpleAsyncTaskExecutor(r -> new Thread(ContextSnapshot.captureAll().wrap(r))));
    }
  }

相关问题