我们的业务逻辑如下:
1和2的先后次序无关,但是1必须先于3、4、5执行
1、编写线程池的配置
@Configuration
public class MyThreadConfig {
@Bean
public ThreadPoolExecutor threadPoolExecutor(){
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
20,
200,
10,
TimeUnit.SECONDS,
new LinkedBlockingDeque<>(100000),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.AbortPolicy());
return threadPoolExecutor;
}
}
但是我们希望核心线程数、最大线程数、线程等待时间都是可配置的(在配置文件中可配置),所以进行如下修改
2、编写与配置文件绑定的配置类
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@ConfigurationProperties(prefix = "gulimall.thread")
@Component
@Data
public class ThreadPoolConfigProperties {
private Integer coreSize;
private Integer maxSize;
private Integer keepAliveTime;
}
3、在配置文件中进行配置
4、修改代码
因为我们将ThreadPoolConfigProperties类作为一个组件加入容器了,所以我们在MyThreadConfig类中可以直接使用
如果没有将ThreadPoolConfigProperties类加入容器,可以在MyThreadConfig添加注解来开启属性配置@EnableConfigurationProperties(ThreadPoolConfigProperties.class)
5、使用异步编写业务
/**
* 商品详情信息
* @param skuId
* @return
*/
@Override
public SkuItemVo info(Long skuId) throws ExecutionException, InterruptedException {
SkuItemVo itemVo = new SkuItemVo();
CompletableFuture<SkuInfoEntity> future01 = CompletableFuture.supplyAsync(() ->{
//1、sku基本信息获取 pms_sku_info
SkuInfoEntity skuInfoEntity = this.getById(skuId);
itemVo.setInfo(skuInfoEntity);
return skuInfoEntity;
}, executor);
CompletableFuture<Void> future02 = future01.thenAcceptAsync((res) -> {
//3、获取spu的销售属性组合
List<SkuItemSaleAttrVo> saleAttr = skuSaleAttrValueService.getSaleAttrsBySpuId(res.getSpuId());
itemVo.setSaleAttr(saleAttr);
}, executor);
CompletableFuture<Void> future03 = future01.thenAcceptAsync((res) -> {
//4、获取spu的介绍
SpuInfoDescEntity spuInfoDesc = spuInfoDescService.getById(res.getSpuId());
itemVo.setDesp(spuInfoDesc);
}, executor);
CompletableFuture<Void> future04 = future01.thenAcceptAsync((res) -> {
//5、获取spu的规格参数信息
List<SpuItemAttrGroupVo> groupAttrs = attrGroupService.getAttrGroupWithAttrsBySpuId(res.getSpuId(), res.getCatalogId());
itemVo.setGroupAttrs(groupAttrs);
}, executor);
//重新开启一个异步
CompletableFuture<Void> future05 = CompletableFuture.runAsync(() -> {
//2、sku的图片信息 pms_sku_images
List<SkuImagesEntity> imagesEntities = skuImagesService.getImagesBySkuId(skuId);
itemVo.setImages(imagesEntities);
}, executor);
//必须所有异步都完成才能返回
CompletableFuture<Void> allOf = CompletableFuture.allOf(future01, future02, future03, future04, future05);
allOf.get();
return itemVo;
}
标签:异步,res,---,itemVo,73,future01,executor,CompletableFuture
From: https://www.cnblogs.com/morehair/p/17103057.html