Spring Boot 使用Sping Boot 异步的自定义ThreadPoolTaskExecutor

6ioyuze2  于 2022-11-23  发布在  Spring
关注(0)|答案(2)|浏览(215)

我有一个Sping Boot 应用程序,它负责通过REST响应请求。我还推送关于我的应用程序调用的指标。由于这是一个单独的任务,我必须立即响应用户,我希望使指标异步发布。所以我使用了:

ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(2);
executor.setMaxPoolSize(2);
executor.setQueueCapacity(500);
executor.setThreadNamePrefix("MyApp-");
executor.initialize();
return executor;

但是,这个线程使用SimpleAsyncTaskExecutor,并且不重用任何线程。
1)如何使用ConcurrentTaskExecutor代替SimpleAsyncTaskExecutor
2)哪种实现最适合我的需求?

tp5buhyn

tp5buhyn1#

要使自定义Executor正常工作,请确保将其注册为Bean,并在使用@Async注解的方法上引用它:

@Bean(name = "transcodingPoolTaskExecutor")
public Executor transcodingPoolTaskExecutor() {
    final ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setCorePoolSize(2);
    executor.setMaxPoolSize(2);
    executor.setQueueCapacity(500);
    executor.setThreadNamePrefix("transcoder-");
    executor.initialize();
    return executor;
}

而在@Service里面是拿着这个方法的:

@Async("transcodingPoolTaskExecutor")
public void transcodeVideo(UUID fileId) {
    mediaFileService.transcodeVideo(fileId);
}
sshcrbum

sshcrbum2#

您也可以通过创建一个实现AsyncConfigurer的Configuration类来重新定义默认执行器。

@EnableAsync
@Configuration
public class AsyncConfig implements AsyncConfigurer {
    @Value("${async.executor.corePoolSize:20}")
    private int corePoolSize;

    @Value("${async.executor.maxPoolSize:100}")
    private int maxPoolSize;

    @Value("${async.executor.queueCapacity:50}")
    private int queueCapacity;

    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(queueCapacity);
        executor.setThreadNamePrefix("Async Executor -");
        executor.initialize();
        return executor;
    }
}

在这种情况下,您不需要在@Async注解中指定执行器名称,Spring将使用您在AsyncConfig中定义的执行器。
它与ygoldt提供的解决方案非常相似,但在这种情况下,您不需要在每个@Async注解中指定执行者的名称,因此它消除了执行者名称中潜在的拼写错误。

相关问题