栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

在平时使⽤多线程的时候⼤多是通过这⼏种⽅式:
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);
    }

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/980907.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号