接口性能优化实战

耗时接口的性能优化

  1. 异步并发执行,CompletableFuture,比如查询商品详情接口,需要查各种表,返回一个大的DTO,可以同时查 item、sku、spu、gnu,然后拼装成一个DTO
  ProductUnitStructure productUnitStructure = productUnitEsSearch.searchByCondition(conditionMap);
    if (isEmpty(productUnitStructure)) {
        return RpcResponseResultUtil.successNoData();
    }
    Long gnuId = productUnitStructure.getGnuId();
    String spuCode = productUnitStructure.getSpuCode();
    String skuCode = productUnitStructure.getSkuCode();

    CompletableFuture productTask = CompletableFuture.supplyAsync(() -> productEsSearch.searchOneProductByCode(skuCode));
    CompletableFuture gnuTask = CompletableFuture.supplyAsync(() -> drugGnuEsSearch.searchByGnuId(gnuId));
    CompletableFuture spuTask = CompletableFuture.supplyAsync(() -> productTemplateEsSearch.searchByCode(spuCode));
    CompletableFuture all = CompletableFuture.allOf(productTask, gnuTask, spuTask);
    all.get();

    ProductStructure productStructure = productTask.get();
    ProductTemplateStructure productTemplateStructure = spuTask.get();
    ProductDrugStructure productDrugStructure = gnuTask.get();
    if (ObjectUtils.isNotEmpty(productStructure)) {
        BeanCopyManualUtils.copySkuStructureToProductDetailDTO(productStructure, productDetailDTO);
    }
    if (ObjectUtils.isNotEmpty(productTemplateStructure)) {
        BeanCopyManualUtils.copySpuStructureToProductDetailDTO(productTemplateStructure, productDetailDTO);
    }
    if (ObjectUtils.isNotEmpty(productDrugStructure)) {
        BeanCopyManualUtils.copyGnuStructureToProductDetailDTO(productDrugStructure, productDetailDTO);
    }
    BeanCopyManualUtils.copyItemStructureToProductDetailDTO(productUnitStructure, productDetailDTO);
  1. 批量操作: list.parallelStream 多线程并发执行
    思路一:一次查批量,思路二:一次查一个,并发执行查

    testList.parallelStream().forEach(element->{
        System.out.println(Thread.currentThread().toString()+element);
    });

你可能感兴趣的:(接口性能优化实战)