SpringBoot 配置异步线程池
1、在 Spring Boot 应用程序的主配置类上添加 @EnableAsync 注解,以启用异步任务的支持,也可以加在你要执行调用异步方法的类上【这个是只在加异步方法的类上起作用】
给要异步的方法添加@Async注解,如果是在主配置类上添加的,直接在方法中添加@Async注解就好了
@EnableAsync
@SpringBootApplication
public class YourApplication {
// ...
}
@Service
public class YourService {
@Async
public void asyncMethod() {
// 异步执行的任务逻辑
// ...
}
}
或者是在你要调用异步的类中进行添加
@Service
@EnableAsync
public class YourService {
//在这里调用异步接口
yourService2.asyncMethod();
}
2、自定义线程池类通过@Configuration交于springboot配置
需要注意的是:任务队列容量不得小于你数据量并发时最大的访问量,否则会导致数据异步接口报错,当次并发的异步接口不再执行
@Configuration
public class ThreadPoolConfig(){
@Bean("threadPooTTaskExecutor")
public TaskExecutor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolsize(20); // 核心线程数
executor.setMaxPoolsize(200); // 最大线程数
executor.setQueueCapacity(2000); // 任务队列容量
executor.setThreadNamePrefix("async-"); // 线程名前缀executor.initialize() ;
return executor;
}
}
也可以在 application.properties 或 application.yml中配置
spring:
task.execution.pool.core-size: 10 # 线程池核心线程数
task.execution.pool.max-size: 20 # 线程池最大线程数
task.execution.pool.queue-capacity: 1000 # 任务队列容量
3、调用异步方法时,Spring Boot 将会自动创建并管理一个线程池,并将异步任务提交给线程池执行。
@Controller
public class YourController {
@Autowired
private YourService yourService;
@GetMapping("/async")
public void asyncEndpoint() {
yourService.asyncMethod(); // 调用异步方法
// ...
}
}
自己根据平时项目中用到的东西做个总结,如果有涉及到侵权行为,请联系我,谢谢~