1 主类上增加启用异步注解
@SpringBootApplication
@EnableAutoConfiguration
@EnableAsync
public class Application {
public static void main(String[] args){
SpringApplication.run(Application.class, args);
}
}
2 配置自己线程池(commonPoolTaskExecutor)
@Configuration
public class ExecutorConfig {
@Bean
public ThreadPoolTaskExecutor commonPoolTaskExecutor(){
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(5);
executor.setMaxPoolSize(10);
executor.setQueueCapacity(100);
executor.setKeepAliveSeconds(300);
executor.setThreadNamePrefix("CommExecutor-");
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
return executor;
}
}
3 定义异步方法
由于spring代理原理,异步方法需要写到单独一个类,由其它类从外部来调用,否则调用本类的@Async不起效的
@Component
public class SmsAlarmTemplate {
@Async("commonPoolTaskExecutor")// 使用自定义的线程池
public void fun(){
// 异步方法
}
}