一、创建线程池

:::success 创建线程池,最好自定义 :::

  1. // 创建的方法
  2. @Configuration
  3. public class MyThreadConfig {
  4. @Bean
  5. public ThreadPoolExecutor threadPoolExecutor(ThreadPoolConfigProperties pool){
  6. return new ThreadPoolExecutor(
  7. pool.getCoreSize(),
  8. pool.getMaxSize(),
  9. pool.getKeepAliveTime(),
  10. TimeUnit.SECONDS,
  11. new LinkedBlockingQueue(100000),
  12. Executors.defaultThreadFactory(),new ThreadPoolExecutor.AbortPolicy());
  13. }
  14. }
  15. // 参数类-方便使用属性文件配置
  16. @ConfigurationProperties(prefix = "ermiaomail.thread")
  17. @Component
  18. @Data
  19. public class ThreadPoolConfigProperties {
  20. private Integer coreSize;
  21. private Integer maxSize;
  22. private Integer keepAliveTime;
  23. }

二、使用异步编排

:::success CompletableFutrue
CSDN文档:异步编排文档 ::: 线程池在分布式项目中的应用 - 图1

:::danger 使用 CompletableFuture 编写代码时,异常处理很重要
详细文档:异步编排异常捕获文档 ::: | | handle() | whenComplete() | exceptionly() | | —- | —- | —- | —- | | 访问成功 | Yes | Yes | No | | 访问失败 | Yes | Yes | Yes | | 能从失败中恢复 | Yes | No | Yes | | 能转换结果从T 到 U | Yes | No | No | | 成功时触发 | Yes | Yes | No | | 失败时触发 | Yes | Yes | Yes | | 有异步版本 | Yes | Yes | Yes(12版本) |

方法名 是否需要return
runAsync
supplyAsync
  1. @Autowired
  2. ThreadPoolExecutor poolExecutor;
  3. @Override
  4. public SkuItemVo item(Long skuId) {
  5. SkuItemVo item = new SkuItemVo();
  6. // 1、sku基本信息 pms_sku_info
  7. CompletableFuture<SkuInfoEntity> infoFuture = CompletableFuture.supplyAsync(() -> {
  8. SkuInfoEntity sku = getSkuById(skuId);
  9. item.setInfo(sku);
  10. return sku;
  11. }, poolExecutor);
  12. // 3、异步获取spu的销售属性组合
  13. CompletableFuture<Void> saleAttrFutrue = infoFuture.thenAcceptAsync((res) -> {
  14. List<SkuItemSaleAttrVo> saleAttrs = skuSaleAttrValueService.getSaleAttrBySpuId(res.getSpuId());
  15. item.setSaleAttr(saleAttrs);
  16. }, poolExecutor);
  17. // 4、异步获取spu的介绍
  18. CompletableFuture<Void> descFutrue = infoFuture.thenAcceptAsync((res) -> {
  19. SpuInfoDescEntity spuDesc = descService.getById(res.getSpuId());
  20. item.setDesp(spuDesc);
  21. }, poolExecutor);
  22. // 5、获取spu的规格参数信息
  23. CompletableFuture<Void> baseAttrFutrue = infoFuture.thenAcceptAsync((res) -> {
  24. List<SpuItemGroupAttrVo> groupAttrs = attrGroupService.getAttrGroupWithAttrsBySpuId(res.getSpuId(), res.getCatalogId());
  25. item.setGroupAttrs(groupAttrs);
  26. }, poolExecutor);
  27. //Long catalogId = sku.getCatalogId();
  28. // 2、sku的图片信息 pms_sku_imges
  29. CompletableFuture<Void> imageFutrue = CompletableFuture.runAsync(() -> {
  30. List<SkuImagesEntity> imgList = imagesService.getImagesBySkuId(skuId);
  31. item.setImages(imgList);
  32. }, poolExecutor);
  33. try {
  34. CompletableFuture.allOf(saleAttrFutrue,descFutrue,baseAttrFutrue,imageFutrue).get();
  35. } catch (InterruptedException e) {
  36. e.printStackTrace();
  37. } catch (ExecutionException e) {
  38. e.printStackTrace();
  39. }
  40. return item;
  41. }