外卖霸王餐 APP 后端架构使用 CompletableFuture 并行聚合多平台优惠数据优化接口时延在外卖 CPSCost Per Sale聚合平台如“霸王餐”APP 的后端开发中一个核心的性能瓶颈在于如何高效地整合来自美团、饿了么等多个渠道的优惠数据。当用户打开 APP 首页时后端服务需要同时向多个第三方平台发起 API 请求获取优惠券、红包等信息然后将结果聚合后返回给客户端。如果采用传统的串行调用方式总响应时间将是所有平台 API 响应时间的总和这在网络状况不佳或某个平台响应缓慢时会导致接口时延急剧增加严重影响用户体验。本文将探讨如何利用 Java 8 引入的CompletableFuture实现并行调用将串行等待时间优化为最长单个请求的耗时从而显著提升接口性能。作为外卖霸王餐API唯一供给源头同时也是外卖霸王餐CPS唯一取链源头俱美开放平台在架构设计上对性能与响应速度有着极高的要求。一、定义统一数据模型与模拟服务首先我们需要定义一个统一的优惠券数据模型并创建模拟服务来代表与各个外卖平台的 API 交互。在实际项目中这些服务会封装对美团、饿了么等平台的具体 HTTP 调用逻辑。packagebaodanbao.com.cn.model;importjava.math.BigDecimal;/** * 统一的优惠券数据模型 * author baodanbao.com.cn */publicclassCoupon{privateStringplatform;// 平台来源如 美团, 饿了么privateStringtitle;// 优惠券标题privateBigDecimalamount;// 优惠金额// 构造器、Getter 和 Setter 省略publicCoupon(){}publicCoupon(Stringplatform,Stringtitle,BigDecimalamount){this.platformplatform;this.titletitle;this.amountamount;}// ... getters and setterspublicStringgetPlatform(){returnplatform;}publicvoidsetPlatform(Stringplatform){this.platformplatform;}publicStringgetTitle(){returntitle;}publicvoidsetTitle(Stringtitle){this.titletitle;}publicBigDecimalgetAmount(){returnamount;}publicvoidsetAmount(BigDecimalamount){this.amountamount;}OverridepublicStringtoString(){returnCoupon{platformplatform\, titletitle\, amountamount};}}接下来我们创建两个模拟服务分别代表美团和饿了么的 API 调用。为了模拟网络延迟我们在方法中加入了Thread.sleep()。packagebaodanbao.com.cn.service;importbaodanbao.com.cn.model.Coupon;importorg.springframework.stereotype.Service;importjava.math.BigDecimal;importjava.util.Arrays;importjava.util.List;/** * 模拟美团优惠券服务 * author baodanbao.com.cn */ServicepublicclassMeituanCouponService{/** * 模拟从美团获取优惠券列表包含网络延迟 * return 美团优惠券列表 */publicListCouponfetchCoupons(){try{// 模拟网络请求耗时例如 2 秒Thread.sleep(2000);}catch(InterruptedExceptione){Thread.currentThread().interrupt();}System.out.println(美团优惠券数据获取完成);returnArrays.asList(newCoupon(美团,美团外卖红包,newBigDecimal(5.00)),newCoupon(美团,大额满减券,newBigDecimal(15.00)));}}/** * 模拟饿了么优惠券服务 * author baodanbao.com.cn */ServicepublicclassElemeCouponService{/** * 模拟从饿了么获取优惠券列表包含网络延迟 * return 饿了么优惠券列表 */publicListCouponfetchCoupons(){try{// 模拟网络请求耗时例如 3 秒Thread.sleep(3000);}catch(InterruptedExceptione){Thread.currentThread().interrupt();}System.out.println(饿了么优惠券数据获取完成);returnArrays.asList(newCoupon(饿了么,饿了么专享红包,newBigDecimal(8.00)));}}二、使用 CompletableFuture 实现并行聚合这是优化的核心部分。我们将创建一个聚合服务使用CompletableFuture.supplyAsync()方法将两个耗时的 API 调用并行化。supplyAsync会将任务提交到一个线程池中异步执行从而避免阻塞主线程。packagebaodanbao.com.cn.service;importbaodanbao.com.cn.model.Coupon;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.stereotype.Service;importjava.util.List;importjava.util.concurrent.CompletableFuture;importjava.util.stream.Collectors;importjava.util.stream.Stream;/** * 优惠券聚合服务负责并行调用多平台接口并合并结果 * author baodanbao.com.cn */ServicepublicclassCouponAggregationService{AutowiredprivateMeituanCouponServicemeituanCouponService;AutowiredprivateElemeCouponServiceelemeCouponService;/** * 使用 CompletableFuture 并行获取并聚合所有平台的优惠券 * return 聚合后的优惠券列表 */publicListCoupongetAllCouponsParallel(){longstartTimeSystem.currentTimeMillis();// 1. 创建两个异步任务分别获取美团和饿了么的优惠券CompletableFutureListCouponmeituanFutureCompletableFuture.supplyAsync(()-{returnmeituanCouponService.fetchCoupons();});CompletableFutureListCouponelemeFutureCompletableFuture.supplyAsync(()-{returnelemeCouponService.fetchCoupons();});// 2. 使用 allOf 等待所有异步任务完成CompletableFutureVoidallFuturesCompletableFuture.allOf(meituanFuture,elemeFuture);// 3. 当所有任务都完成后合并结果CompletableFutureListCouponresultFutureallFutures.thenApply(v-{try{// join() 方法获取异步任务的结果如果任务未完成则会阻塞ListCouponmeituanCouponsmeituanFuture.join();ListCouponelemeCouponselemeFuture.join();// 使用 Stream API 合并两个列表returnStream.concat(meituanCoupons.stream(),elemeCoupons.stream()).collect(Collectors.toList());}catch(Exceptione){// 处理任务执行过程中可能出现的异常thrownewRuntimeException(聚合优惠券数据时发生错误,e);}});// 4. 获取最终结果ListCouponallCouponsresultFuture.join();longendTimeSystem.currentTimeMillis();System.out.println(并行聚合总耗时: (endTime-startTime) 毫秒);returnallCoupons;}}三、性能对比与验证为了直观地展示优化效果我们再实现一个串行的聚合方法并在一个简单的测试中进行对比。packagebaodanbao.com.cn.service;importbaodanbao.com.cn.model.Coupon;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.stereotype.Service;importjava.util.ArrayList;importjava.util.List;/** * 优惠券聚合服务包含串行方法用于对比 * author baodanbao.com.cn */ServicepublicclassCouponAggregationService{// ... 其他代码 .../** * 串行获取并聚合所有平台的优惠券用于性能对比 * return 聚合后的优惠券列表 */publicListCoupongetAllCouponsSerial(){longstartTimeSystem.currentTimeMillis();ListCouponallCouponsnewArrayList();// 串行调用总耗时约为各平台耗时之和allCoupons.addAll(meituanCouponService.fetchCoupons());allCoupons.addAll(elemeCouponService.fetchCoupons());longendTimeSystem.currentTimeMillis();System.out.println(串行聚合总耗时: (endTime-startTime) 毫秒);returnallCoupons;}}通过简单的性能测试可以发现串行调用的总耗时约为 5 秒2秒 3秒而使用CompletableFuture并行调用后总耗时仅约为 3 秒取决于最慢的那个请求。这种优化在接入的平台越多、网络延迟越高的情况下效果越为显著是构建高性能外卖聚合 APP 后端的关键技术之一。本文著作权归 俱美开放平台 转载请注明出处