Search code examples
springspring-bootmicrometer-tracing

Spring Boot 3 Upgrade Executor context propagation sleuth to micrometer tracing


I am migrating my project from Spring boot version 2.7.4 to version 3.2.2. i need to use micrometer instead of sleuth how should I edit the "Executor" BEAN I mentioned below for asynchronous?
What should I use instead of LazyTraceExecutor class?

@Bean("asyncExecutor")
    public Executor getAsyncExecutor(BeanFactory beanFactory) {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.setThreadNamePrefix("Async-");
        executor.setTaskDecorator(new ContextDecorator());
        executor.initialize();

        return new LazyTraceExecutor(beanFactory, executor);
    }

Solution

  • I rewrote the configuration as follows:

    1. I left the creation of ThreadPoolTaskExecutor
    @Configuration
    public class AppConfiguration {
    
        @Bean
        public ThreadPoolTaskExecutor micrometerThreadPoolTaskExecutor(AppProperties appConfig) {
            return new TaskExecutorBuilder()
                            .maxPoolSize(appConfig.getThreadPoolMaxSize())
                            .corePoolSize(appConfig.getThreadPoolCoreSize())
                            .threadNamePrefix(appConfig.getThreadPoolPrefix())
                            .build();
        }
    }
    
    1. Micrometer tracing configuration
    @Configuration(proxyBeanMethods = false)
    public class TracingAsyncConfiguration implements AsyncConfigurer {
    
        private final ThreadPoolTaskExecutor micrometerTaskExecutor;
    
        public TracingAsyncConfiguration(@Qualifier("micrometerThreadPoolTaskExecutor") ThreadPoolTaskExecutor micrometerTaskExecutor) {
            this.micrometerTaskExecutor = micrometerTaskExecutor;
        }
    
        @Override
        public Executor getAsyncExecutor() {
            return ContextExecutorService.wrap(micrometerTaskExecutor.getThreadPoolExecutor(), ContextSnapshotFactory.builder().build()::captureAll);
        }
    }
    

    A very similar issue has been discussed here