首页 > 解决方案 > 如何在@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. 如何解决?

标签: javaspringspring-bootasynchronousscheduled-tasks

解决方案


推荐阅读