异步化实现
一、优惠券改为异步方法
- 启动Application类中添加异步注解@EnableAsync
Controller中改写相应方法,返回Future类型
12345678//可领取的券Future<BaseResponseVo<List<CouponBatchActiveVo>>> skuCouponResultFuture = promotionAsyncService.findJoinActives(jdUserId,Integer.valueOf(cid),itemId,Integer.valueOf(venderId),tenantId);//本品可用的券Future<BaseResponseVo<List<ItemCouponVO>>> currentSkuCouponResultFuture = promotionAsyncService.findCanUseCoupons(jdUserId,Integer.valueOf(cid), itemId,Integer.valueOf(venderId),tenantId);//已领取的券Future<BaseResponseVo<List<CouponBatchActiveExtVo>>> userConponResultFuture = promotionAsyncService.queryUsableCouponPage(jdUserId, "1",tenantId, itemId);添加相应的AsyncService接口
12//可领取的券-接口Future<BaseResponseVo<List<CouponBatchActiveVo>>> findJoinActives(String jdUserId, int cId, Long skuId, int venderId, Long tenantId);添加相应的AsyncServiceImpl,添加@Async注解,调用非Async的Service方法获取结果,包装成AsyncResult类型返回
123456public Future<BaseResponseVo<List<CouponBatchActiveVo>>> findJoinActives(String jdUserId, int cId, Long skuId, int venderId, Long tenantId) {LOGGER.info("--------PromotionAsyncServiceImpl.findJoinActives------start");BaseResponseVo<List<CouponBatchActiveVo>> responseVo = promotionService.findJoinActives(jdUserId,cId,skuId,venderId,tenantId);return new AsyncResult<BaseResponseVo<List<CouponBatchActiveVo>>>(responseV);}Future结果获取,使用get()方法
12345678910111213Long startTime = System.currentTimeMillis();while(true){if(skuCouponResultFuture.isDone() && currentSkuCouponResultFuture.isDone()&& userConponResultFuture.isDone()){break;}if ((System.currentTimeMillis() - startTime) > 2000) {break;}}BaseResponseVo<List<CouponBatchActiveVo>> skuCouponResult = skuCouponResultFuture.get();BaseResponseVo<List<ItemCouponVO>> currentSkuCouponResult = currentSkuCouponResultFuture.get();BaseResponseVo<List<CouponBatchActiveExtVo>> userConponResult = userConponResultFuture.get();
二、通过Feign调用的Controller修改成异步
直接新建一个Service和对应的ServiceImpl,新建@Async方法,把通过client调用的方法包含在方法体内,实现异步。