Spring里如何实现方法的异步执行
如题:在Spring里面如何让一个方法异步执行?答案是@Async注解,让一个方法异步执行的条件:
- 开启异步执行:@EnableAsync
- 配置线程池,非必须,没有则用默认线程池
- Bean方法指定为异步:@Async
接下来分步骤详细讲解每一步
开启异步执行:@EnableAsync
只有开启@EnableAsync,打上@Async注解的方法才能异步执行
@Configuration
@EnableAsync
public class AsyncConfig {
// ...
}
配置线程池
定制线程池需要实现AsyncConfigurer
,并提供合适的线程池和异常处理器
@Configuration
@ComponentScan
@EnableAsync
public class AsyncConfig implements AsyncConfigurer {
@Bean
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(4);
executor.setMaxPoolSize(10);
executor.setQueueCapacity(11);
executor.setThreadNamePrefix("MyExecu