
- 开启异步调用支持
@EnableAsync 启动类使用注解开启异步调用
2. 添加异步方法
@Async
public void sendSms(){
System.out.println("@Async");
}
3.配置线程池
@Configuration
@EnableAsync
public class ExecutorConfig {
@Bean
public Executor asyncServiceExecutor() {
LoggerUtil.logger().info("start asyncServiceExecutor");
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
//配置核心线程数
executor.setCorePoolSize(5);
//配置最大线程数
executor.setMaxPoolSize(5);
//配置队列大小
executor.setQueueCapacity(1000);
//配置线程池中的线程的名称前缀
executor.setThreadNamePrefix("async-service-");
// rejection-policy:当pool已经达到max size的时候,如何处理新任务
// CALLER_RUNS:不在新线程中执行任务,而是有调用者所在的线程来执行
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
//执行初始化
executor.initialize();
return executor;
}
}
4.使用注解添加到线程池
@Async("asyncServiceExecutor")
public void sendSms(){
System.out.println("@Async");
}
注意事项:1.在@SpringBootApplication启动类 添加注解@EnableAsync
2.异步方法使用注解@Async ,返回值为void或者Future
3.切记一点 ,异步方法和调用方法一定要* 写在不同的类中 *,如果写在一个类中, 是没有效果的