Spring是通過(guò)任務(wù)執(zhí)行器(TaskExecutor)來(lái)實(shí)現(xiàn)多線程和并發(fā)編程,使用ThreadPoolTaskExecutor來(lái)創(chuàng)建一個(gè)基于線城池的TaskExecutor。在使用線程池的大多數(shù)情況下都是異步非阻塞的。我們配置注解@EnableAsync可以開(kāi)啟異步任務(wù)。然后在實(shí)際執(zhí)行的方法上配置注解@Async上聲明是異步任務(wù)。
------摘抄自書(shū)籍《JavaEE開(kāi)發(fā)的顛覆者 Spring Boot實(shí)戰(zhàn) 》
關(guān)鍵代碼:
配置類(lèi)代碼:
@Configuration
@EnableAsync
public class AsyncConfig implements AsyncConfigurer {
@Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
//核心線程數(shù)
taskExecutor.setCorePoolSize(20);
//最大線程數(shù)
taskExecutor.setMaxPoolSize(40);
taskExecutor.setQueueCapacity(100);
executor.setKeepAliveSeconds(60);
executor.setThreadNamePrefix("taskExecutor-");
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
executor.setWaitForTasksToCompleteOnShutdown(true);
executor.setAwaitTerminationSeconds(60);
taskExecutor.initialize();
return taskExecutor;
}
}
任務(wù)執(zhí)行代碼:
@Servicepublic class AsyncService {
@Async
public void executeAsync() {
//業(yè)務(wù)邏輯代碼
......
}
}
通過(guò)@Async注解表明該方法是異步方法,如果注解在類(lèi)上,那表明這個(gè)類(lèi)里面的所有方法都是異步的。這里的方法自動(dòng)被注入使用配置的ThreadPoolTaskExecutor作為T(mén)askExecutor。