From d49ec200328bf8d0de0671b1a788663d2661b6b6 Mon Sep 17 00:00:00 2001 From: yuanye <418471657@qq.com> Date: Mon, 27 May 2024 13:59:06 +0800 Subject: [PATCH] Changes --- .../hfkj/service/goods/GoodsMsgService.java | 2 +- .../goods/impl/GoodsMsgServiceImpl.java | 43 ++++++++++++------- 2 files changed, 28 insertions(+), 17 deletions(-) diff --git a/service/src/main/java/com/hfkj/service/goods/GoodsMsgService.java b/service/src/main/java/com/hfkj/service/goods/GoodsMsgService.java index 09d5523..0764696 100644 --- a/service/src/main/java/com/hfkj/service/goods/GoodsMsgService.java +++ b/service/src/main/java/com/hfkj/service/goods/GoodsMsgService.java @@ -83,6 +83,6 @@ public interface GoodsMsgService { * @param type 1: 增加库存 2: 减少库存 * @return */ - void editSaleNum(Long goodsId , Integer num , Integer type) throws Exception; + void editSaleNum(Long goodsId , Integer num , Integer type); } diff --git a/service/src/main/java/com/hfkj/service/goods/impl/GoodsMsgServiceImpl.java b/service/src/main/java/com/hfkj/service/goods/impl/GoodsMsgServiceImpl.java index 1191df1..f1d0ae6 100644 --- a/service/src/main/java/com/hfkj/service/goods/impl/GoodsMsgServiceImpl.java +++ b/service/src/main/java/com/hfkj/service/goods/impl/GoodsMsgServiceImpl.java @@ -1,5 +1,8 @@ package com.hfkj.service.goods.impl; +import com.hfkj.common.exception.ErrorCode; +import com.hfkj.common.exception.ErrorHelp; +import com.hfkj.common.exception.SysCode; import com.hfkj.dao.GoodsMsgMapper; import com.hfkj.entity.GoodsBrand; import com.hfkj.entity.GoodsMsg; @@ -101,33 +104,41 @@ public class GoodsMsgServiceImpl implements GoodsMsgService { } @Override - public void editSaleNum(Long goodsId, Integer num , Integer type) throws Exception { + public void editSaleNum(Long goodsId, Integer num , Integer type) { String key = "GOODS" + goodsId; - // 分布式锁占坑 - Boolean lock = redisTemplate.opsForValue().setIfAbsent(key, goodsId); + try { + // 分布式锁占坑 + Boolean lock = redisTemplate.opsForValue().setIfAbsent(key, goodsId); - GoodsMsg goodsMsg = queryDetail(goodsId); + GoodsMsg goodsMsg = queryDetail(goodsId); - if (goodsMsg != null) { + if (goodsMsg != null) { - if(Boolean.TRUE.equals(lock)) { + if(Boolean.TRUE.equals(lock)) { - if (type == 1) { - goodsMsg.setSaleNum(goodsMsg.getSaleNum() + num); - } else if (type == 2){ - goodsMsg.setSaleNum(goodsMsg.getSaleNum() - num); + if (type == 1) { + goodsMsg.setSaleNum(goodsMsg.getSaleNum() + num); + } else if (type == 2){ + goodsMsg.setSaleNum(goodsMsg.getSaleNum() - num); + } + + update(goodsMsg); + } else { + // 加锁失败,重试 + Thread.sleep(100); + editSaleNum(goodsId , num , type); } - update(goodsMsg); - } else { - // 加锁失败,重试 - Thread.sleep(100); - editSaleNum(goodsId , num , type); - } + } + } catch (Exception e) { + e.printStackTrace(); + } finally { + // 删除key,释放锁 + redisTemplate.delete(key); } }