CompletableFuture异步编排实战
Alex Chen | 2026-09-02T10:21:00 | Java, Spring Boot
用CompletableFuture优化商品详情页查询,从串行800ms降到并行200ms的实战经验
# CompletableFuture异步编排实战 最近优化商品详情页接口,原来是串行查询4个服务,800ms。用CompletableFuture改成并行后,直接降到200ms。 ## 串行 vs 并行 ```java // 改造前:串行调用,慢得要死 public ProductDetail getDetail(Long id) { ProductInfo info = productService.getInfo(id); // 200ms List skus = skuService.list(id); // 200ms List reviews = reviewService.list(id); // 200ms ShopInfo shop = shopService.getInfo(info.getShopId()); // 200ms // 总计约800ms return new ProductDetail(info, skus, reviews, shop); } // 改造后:并行调用 public ProductDetail getDetailAsync(Long id) { CompletableFuture infoFuture = CompletableFuture.supplyAsync(() -> productService.getInfo(id), executor); CompletableFuture> skuFuture = CompletableFuture.supplyAsync(() -> skuService.list(id), executor); CompletableFuture> reviewFuture = CompletableFuture.supplyAsync(() -> reviewService.list(id), executor); // shop依赖info的结果,用thenCompose串联 CompletableFuture shopFuture = infoFuture .thenComposeAsync(info -> CompletableFuture.supplyAsync( () -> shopService.getInfo(info.getShopId()), executor )); // 等所有任务完成 CompletableFuture.allOf(infoFuture, skuFuture, reviewFuture, shopFuture).join(); // 总计约400ms(info+shop串行200+200,其他并行) return new ProductDetail(infoFuture.join(), skuFuture.join(), reviewFuture.join(), shopFuture.join()); } ``` **注意事项**:一定要自定义线程池,别用默认的ForkJoinPool.commonPool(),否则一个慢任务会拖垮所有异步调用。