自定义线程池 config
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| package com.jhj.gulimall.product.config;
import org.springframework.beans.factory.annotation.Configurable; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration;
import java.util.concurrent.*;
@Configuration public class MyThreadConfig {
@Bean public ThreadPoolExecutor threadPoolExecutor(ThreadPoolConfigProperties pool){ return new ThreadPoolExecutor(pool.getCoreSize(), pool.getMaxSize(), pool.getKeepAliveTime(), TimeUnit.SECONDS, new LinkedBlockingDeque<>(100000), Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy()); } }
|
Properties
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| package com.jhj.gulimall.product.config;
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; }
|
yml
1 2 3 4 5
| gulimall: thread: coreSize: 20 maxSize: 50 keepAliveTime: 1000
|
补充
springboot自带的线程池
让任务加入线程池 在类上使用@EnableAsync 在方法上使用@Async 自动配置类为TaskExecutionAutoConfiguration 属性绑定在TaskExecutionProperties
1 2 3 4 5 6 7 8
| spring: task: execution: pool: #线程数 core-size: 20 #最大数 max-size: 50
|
使用
@Resource
TaskExecutor taskExecutor;
异步编排
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| @Override public SkuItemVo item(Long skuId) throws ExecutionException, InterruptedException { SkuItemVo skuItemVo=new SkuItemVo();
CompletableFuture<SkuInfoEntity> infoFuture = CompletableFuture.supplyAsync(() -> { SkuInfoEntity info = getById(skuId); skuItemVo.setInfo(info); return info; }, threadPoolExecutor);
CompletableFuture<Void> saleAttrFuture = infoFuture.thenAcceptAsync((res) -> { List<SkuItemSaleAttrVo> skuItemSaleAttrVos = skuSaleAttrValueService.getSaleAttrsBySpuId(res.getSpuId()); skuItemVo.setSaleAttr(skuItemSaleAttrVos); }, threadPoolExecutor);
CompletableFuture<Void> descFuture =infoFuture.thenAcceptAsync((res)->{ SpuInfoDescEntity spuInfoDescEntity = spuInfoDescService.getById(res.getSpuId()); skuItemVo.setDesc(spuInfoDescEntity); },threadPoolExecutor);
CompletableFuture<Void> baseAttrFuture=infoFuture.thenAcceptAsync((res)->{ List<SkuItemAttrGroupVo> attrGroupVos=attrGroupService.getAttrGroupWithAttrsBySpuId(res.getSpuId(),res.getCatalogId()); skuItemVo.setGroupAttrs(attrGroupVos); },threadPoolExecutor);
CompletableFuture<Void> imageFuture = CompletableFuture.runAsync(() -> { List<SkuImagesEntity> images = imagesService.getImagesBySkuId(skuId); skuItemVo.setImages(images); }, threadPoolExecutor);
CompletableFuture.allOf(saleAttrFuture,descFuture,baseAttrFuture,imageFuture).get(); return skuItemVo; }
|
作者声明