From f8aa83539e3cd59bdb02c5f1c72c7f216aee0028 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=83=9D=E5=85=88=E7=91=9E?= <1490493387@qq.com> Date: Sat, 26 Feb 2022 23:23:20 +0800 Subject: [PATCH] =?UTF-8?q?fix(OrderServiceImpl.java):=20tryLock=E9=87=8A?= =?UTF-8?q?=E6=94=BE=E9=94=81=E5=85=88=E5=88=A4=E6=96=AD=E9=94=81=E6=98=AF?= =?UTF-8?q?=E5=90=A6=E5=B7=B2=E7=BB=8F=E8=A2=AB=E9=87=8A=E6=94=BE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../oms/service/impl/OrderServiceImpl.java | 20 ++++++------------- 1 file changed, 6 insertions(+), 14 deletions(-) diff --git a/mall-oms/oms-boot/src/main/java/com/youlai/mall/oms/service/impl/OrderServiceImpl.java b/mall-oms/oms-boot/src/main/java/com/youlai/mall/oms/service/impl/OrderServiceImpl.java index 6baf9a0b9..bfd8a225b 100644 --- a/mall-oms/oms-boot/src/main/java/com/youlai/mall/oms/service/impl/OrderServiceImpl.java +++ b/mall-oms/oms-boot/src/main/java/com/youlai/mall/oms/service/impl/OrderServiceImpl.java @@ -218,8 +218,8 @@ public class OrderServiceImpl extends ServiceImpl impleme boolean flag = false; try { - //尝试获取锁,获取不到会立马返回 false - flag = lock.tryLock(0L, 10L, TimeUnit.SECONDS); + // 尝试加锁,最多等待1秒,上锁10秒后自动解锁 + flag = lock.tryLock(1L, 10L, TimeUnit.SECONDS); if (!flag) { throw new BizException("订单不可重复支付"); } @@ -232,25 +232,19 @@ public class OrderServiceImpl extends ServiceImpl impleme result = (T) wxJsapiPay(appId, order); break; default: - case BALANCE: result = (T) balancePay(order); + break; } - // 扣减库存 Result deductStockResult = skuFeignClient.deductStock(order.getOrderSn()); - if (!Result.isSuccess(deductStockResult)) { - throw new BizException("扣减商品库存失败"); - } + Assert.isTrue(Result.isSuccess(deductStockResult), "扣减商品库存失败"); return result; } catch (InterruptedException e) { log.error(e.getMessage(), e); throw new BizException("锁订单异常"); - } catch (Exception e) { - //异常继续往上抛 - throw e; } finally { //释放锁 - if (flag) { + if (flag && lock.isLocked()) { lock.unlock(); } } @@ -268,9 +262,7 @@ public class OrderServiceImpl extends ServiceImpl impleme // 扣减余额 Long payAmount = order.getPayAmount(); Result deductBalanceResult = memberFeignClient.deductBalance(payAmount); - if (!Result.isSuccess(deductBalanceResult)) { - throw new BizException("扣减账户余额失败"); - } + Assert.isTrue(Result.isSuccess(deductBalanceResult), "扣减账户余额失败"); // 更新订单状态 order.setStatus(OrderStatusEnum.PAYED.getCode());