耗时接口的性能优化
- 异步并发执行,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<ProductStructure> productTask = CompletableFuture.supplyAsync(() -> productEsSearch.searchOneProductByCode(skuCode));
CompletableFuture<ProductDrugStructure> gnuTask = CompletableFuture.supplyAsync(() -> drugGnuEsSearch.searchByGnuId(gnuId));
CompletableFuture<ProductTemplateStructure> spuTask = CompletableFuture.supplyAsync(() -> productTemplateEsSearch.searchByCode(spuCode));
CompletableFuture<Void> 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);
- 批量操作: list.parallelStream 多线程并发执行
思路一:一次查批量,思路二:一次查一个,并发执行查
testList.parallelStream().forEach(element->{
System.out.println(Thread.currentThread().toString()+element);
});