java - 如何在@Scheduled 中运行@Async 方法
问题描述
@Scheduled
我已经阅读了很多关于在 Spring 中使用with的问题和答案@Async
,但没有人解决我的问题,我的异步方法仍然运行单线程。所以这是我的配置类:
@EnableScheduling
@EnableAsync
@Configuration
@RequiredArgsConstructor
public class SchedulerConfiguration {
private final ThreadPoolProperties threadPoolProperties;
@Bean
public TaskExecutor commonTaskExecutor() {
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
taskExecutor.setCorePoolSize(threadPoolProperties.getCorePoolSize()); // 10
taskExecutor.setMaxPoolSize(threadPoolProperties.getMaxPoolSize()); // 20
taskExecutor.setQueueCapacity(threadPoolProperties.getQueueCapacity()); // 5
taskExecutor.setThreadNamePrefix("TEST");
taskExecutor.initialize();
return taskExecutor;
}
}
然后我们有一个带有@Scheduled
方法的bean:
@Component
@RequiredArgsConstructor
public class ScheduledTask {
private final ConfirmReservationTask confirmReservationTask;
@Scheduled(cron = "${booking.scheduler.confirmReservationsCron}")
public void process() {
confirmReservationTask.confirmReservations();
}
}
最后,另一个带有方法的bean(避免异步处理的自注入和代理问题)@Async
:
@Log4j2
@Component
@RequiredArgsConstructor
public class ConfirmReservationTask {
private final ReservationService reservationService;
@Async("commonTaskExecutor")
public void confirmReservations() {
...
}
}
不幸的是,此解决方案仅适用于一个线程,但是,该方法使用正确的ThreadExecutor
. 如何解决?
解决方案
推荐阅读
- c# - C# 找不到关于自动更新文本框 WITH 计算的初学者解释
- java - 重新排列一个数组,使得 arr[i] = i
- cordova - 在 Cordova 插件中包含 Storyboard 或 xib 文件
- php - CURL 帖子无法将 csv 数据上传到 blaynmail
- android - 在 LinearLayout 中查找 LinearLayout 的子项
- bash - 如何在不使用重定向运算符的情况下写入文件?
- for-loop - 带有 StringBuilder 的 Java 循环逻辑 (Hangman)
- java - 功能文件中的 testdata 列数是否有任何限制 - selenium java
- c# - 从 JSON Schema 为 Sabre REST API 生成 C# 模型类
- python - Selenium 点击在 Chrome 中不起作用