看看类型 AsyncConfigurer , AsyncConfigurerSupport ,和 SchedulingConfigurer 。它们是您可以用来增强您的帮助类型 @Configuration 具有异步/调度配置的类。
AsyncConfigurer
AsyncConfigurerSupport
SchedulingConfigurer
@Configuration
所有这些,以及javadoc @EnabledAsync ,您将找到设置异步/调度所需的所有设置方法 @Configuration 类。
@EnabledAsync
给出的例子等同于
@Configuration @EnableAsync public class AppConfig implements AsyncConfigurer { @Bean public MyAsyncBean asyncBean() { return new MyAsyncBean(); } @Override public Executor getAsyncExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(7); executor.setMaxPoolSize(42); executor.setQueueCapacity(11); executor.setThreadNamePrefix("MyExecutor-"); executor.initialize(); return executor; } @Override public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() { return new MyAsyncUncaughtExceptionHandler(); } }
同
<beans> <task:annotation-driven executor="myExecutor" exception-handler="exceptionHandler"/> <task:executor id="myExecutor" pool-size="7-42" queue-capacity="11"/> <bean id="asyncBean" class="com.foo.MyAsyncBean"/> <bean id="exceptionHandler" class="com.foo.MyAsyncUncaughtExceptionHandler"/> </beans>
SchedulingConfigurer 有一个类似的设置 task:scheduler 。
task:scheduler
如果你想要更精细的控制,你可以另外实现 SchedulingConfigurer 和/或 AsyncConfigurer 接口。
如下,
请注意游泳池,
@Configuration @EnableScheduling public class CronConfig implements SchedulingConfigurer{ @Override public void configureTasks(ScheduledTaskRegistrar taskRegistrar) { taskRegistrar.setScheduler(taskExecutor()); } @Bean(destroyMethod="shutdown") public Executor taskExecutor() { return Executors.newScheduledThreadPool(10); } }
对于Asyncs,
@Configuration @EnableAsync public class AsyncConfig implements AsyncConfigurer { @Override public Executor getAsyncExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(5); executor.setMaxPoolSize(10); executor.setQueueCapacity(100); executor.initialize(); return executor; } @Override public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() { return new SimpleAsyncUncaughtExceptionHandler(); } }
注意 @EnableAsync 和 @EnableScheduling 必须在那里工作。
@EnableAsync
@EnableScheduling