Java 如何在@Scheduled方法内运行@Async方法
我已经阅读了很多关于在Spring中使用@Scheduled和@Async的问题和答案,但是没有人解决我的问题,我的异步方法仍然运行单线程。下面是我的配置类:Java 如何在@Scheduled方法内运行@Async方法,java,spring,spring-boot,asynchronous,scheduled-tasks,Java,Spring,Spring Boot,Asynchronous,Scheduled Tasks,我已经阅读了很多关于在Spring中使用@Scheduled和@Async的问题和答案,但是没有人解决我的问题,我的异步方法仍然运行单线程。下面是我的配置类: @EnableScheduling @EnableAsync @Configuration @RequiredArgsConstructor public class SchedulerConfiguration { private final ThreadPoolProperties threadPoolProperties;
@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 method的bean:
@Component
@RequiredArgsConstructor
public class ScheduledTask {
private final ConfirmReservationTask confirmReservationTask;
@Scheduled(cron = "${booking.scheduler.confirmReservationsCron}")
public void process() {
confirmReservationTask.confirmReservations();
}
}
最后,使用@Async方法创建另一个bean(以避免异步处理中的自注入和代理问题):
@Log4j2
@Component
@RequiredArgsConstructor
public class ConfirmReservationTask {
private final ReservationService reservationService;
@Async("commonTaskExecutor")
public void confirmReservations() {
...
}
}
不幸的是,此解决方案只能在一个线程中工作,但是该方法使用了正确的ThreadExecutor。如何解决它?您好,您如何定义此解决方案在一个线程上工作?默认情况下,@计划在一个线程上工作,但随后将执行传递给
commonTaskExecutor
。尝试通过jconsole
@shadownindzya查看所有当前活动线程。我在异步方法的循环中进行了数千次操作,并在每次迭代中记录当前线程名称。我复制了您的配置,所有工作都按预期进行``16:27:15.001信息5927---[pool-1-thread-1]stckovflw.example.ScheduledTask:start schedule at thread=pool-1-thread-1 16:27:15.004 INFO 5927---[pool-1-thread-1]stckovflw.example.ScheduledTask:end schedule at thread=pool-1-thread-1 16:27:15.008 INFO 5927---[TEST1]s.example.ConfirmReservationTask:在TEST1上运行confirmReservation16:27:25.008信息5927---[TEST1]s.example.ConfirmReservationTask:在TEST1``上运行confirmReservations,使用jconsole我看到-pool-1-thread-1
调度执行器的线程。和公共执行器池的TEST1,TEST2,…
threads。@shadownindzya尝试将当前线程名记录在循环中10000次,您将始终获得TEST1 thread,至少对我来说它是这样工作的