使用Spring Boot Async定制ThreadPoolTask​​Executor

时间:2016-12-09 21:00:38

标签: java asynchronous spring-boot threadpool

我有一个Spring 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)哪种实施最适合我的需求?

1 个答案:

答案 0 :(得分:2)

要使您的自定义执行器正常工作,请确保将其注册为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);
}