springboot中的@EnableAsync注解和@Async注解实现异步执⾏任务

发布时间: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);
    }

ItVuer - 免责声明 - 关于我们 - 联系我们

本网站信息来源于互联网,如有侵权请联系:561261067@qq.com

桂ICP备16001015号