1.在启动类上或者在异步处理类上添加@EnableAsync注解 !!!!!!
2.可以自定义创建线程池
- 如果不用可以跳过spring会默认使用线程池
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
@Configuration
public class ThreadPoolConfig {
/**
* 线程池任务执行器
* @return
*/
@Bean("manifestOperationExecutor")
public Executor manifestOperationExecutor() {
// 创建线程池
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(5); // 设置核心池大小
executor.setMaxPoolSize(10); // 设置最大池大小,只有在缓冲队列满了之后才会申请超过核心线程数的线程
executor.setQueueCapacity(100); // 设置队列容量
executor.setKeepAliveSeconds(60); // 设置保持活动秒数,当超过了核心线程数之外的线程在空闲时间到达之后会被销毁
executor.setThreadNamePrefix("自定义线程Thread-"); // 设置线程名称前缀
// 设置拒绝的执行处理策略
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
return executor;
}
}
3.创建异步处理类
- 单独创建一个异步处理类,在异步处理类中编写需要异步调用的方法。在service中注入异步类在进行调用
// @Async("manifestOperationExecutor") :指定使用线程池名称
@Async("manifestOperationExecutor")
public void settleDataSyn(String str) {
//异步任务逻辑
System.out.println("异步任务执行成功 :"+str);
}
注意:
1.被@Async注解的方法必须是public的,这样方法才可以被代理。
2.不能在同一个类中调用@Async方法,因为同一个类中调用会绕过方法代理,调用的是实际的方法。