发布时间:2022-09-10 18:00
在平时使⽤多线程的时候⼤多是通过这⼏种⽅式:
1. 实现Thread接
2. 继承Runable类
3. 使⽤线程池
但是在springboot中提供了中通过@Async和@EnableAsync实现多线程功能,将@EnableAsync注解加到创建线程池的配置类上(使⽤@Configuration注解修饰的类),将@Async注解加到需要异步执⾏的任务上,详情如下。
/**
* 任务线程池
*/
@EnableAsync
@Configuration
public class ExecutorPoolConfig implements WebMvcConfigurer {
@Bean("executor")
public Executor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(8);
executor.setMaxPoolSize(20);
executor.setQueueCapacity(20);
executor.setKeepAliveSeconds(60);
executor.setThreadNamePrefix("task-");
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
return executor;
}
@Override
public void configureAsyncSupport(AsyncSupportConfigurer configurer) {
configurer.setDefaultTimeout(7 * 1000);
configurer.setTaskExecutor((ThreadPoolTaskExecutor)taskExecutor());
configurer.registerCallableInterceptors(timeoutCallableProcessingInterceptor());
}
@Bean
public TimeoutCallableProcessingInterceptor timeoutCallableProcessingInterceptor() {
return new TimeoutCallableProcessingInterceptor();
}
}
/**
* 异步任务执行器
*/
@Slf4j
@Component
public class TaskExecutor {
@Async("executor")
public void updateGoodsStoneAndStatus() {
log.info("开始异步执行[更新数据库商品表和库存]任务");
long start = System.currentTimeMillis();
List
updateGoodsList=updateDistribGoodsMapper.getDistribPoolGoodList();
log.info("开始异步执行[更新数据库商品表和库存]任务,批次id:{},", updateGoodsList);
distribGoodsStockService.updateGoodsStone(updateGoodsList);
long end = System.currentTimeMillis();
log.info("完成异步执行[更新数据库商品表和库存]任务,总共耗时:{}毫秒", (end - start));
}
}
@Override
public List getDistribPoolGoodListByPage(String poolId) throws CustomerException {
List list =distribGoodsMapper.getDistribPoolGoodListByPage(poolId);
taskExecutor.updateGoodsStoneAndStatus();
return CollectionsUtils.convertList2List(list, DistribGoodsRespDTO.class);
}