注解
@Async、@EnableAsync
在springboot项目中,基于@Async注解的方法称为异步方法,异步方法在执行的时候,会在一个单独的线程中执行,无需等待即可执行下一个线程。而@Async需要配合@EnableAsync进行使用,@EnableAsync注解使用来开启异步线程的,使@Async起作用;废话不多说,上代码
启动类添加注解
@EnableAsync
@SpringBootApplication
@ForestScan(basePackages = "com.xxxx")
public class BuildApplication {
public static void main(String[] args) {
SpringApplication.run(BuildApplication.class, args);
}
}
配置线程池
@EnableAsync
@Configuration
public class TaskExecutePool {
@Bean(name = "asyncPackExecutor")
public Executor asyncPackExecutor() {
log.info("asyncPackExecutor begin.");
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(10);
executor.setMaxPoolSize(20);
executor.setQueueCapacity(10);
executor.setKeepAliveSeconds(600);
executor.setThreadNamePrefix("async-pack-");
// 被拒绝时,抛出异常
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
executor.initialize();
return executor;
}
业务类调用
@Async("asyncPackExecutor")
public void doAsyncPack(MrProject mrProject, Long packId, PackReq req) {
log.info(
"{} >>>>>>>>> For {} Process PackTask Thread Begin...",
Thread.currentThread().getName(),
packId);
// 业务代码
}