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