From 9b96873439dee87f0dcf5850ba6475dbe476f0e5 Mon Sep 17 00:00:00 2001 From: yuanye <418471657@qq.com> Date: Fri, 24 May 2024 16:25:50 +0800 Subject: [PATCH] Changes --- .../hfkj/service/goods/GoodsMsgService.java | 2 +- .../goods/impl/GoodsMsgServiceImpl.java | 26 ++++++++++++++++--- 2 files changed, 24 insertions(+), 4 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 09f9b08..081c9e4 100644 --- a/service/src/main/java/com/hfkj/service/goods/GoodsMsgService.java +++ b/service/src/main/java/com/hfkj/service/goods/GoodsMsgService.java @@ -82,6 +82,6 @@ public interface GoodsMsgService { * @param num * @return */ - void addSaleNum(Long goodsId , Integer num); + void addSaleNum(Long goodsId , Integer num) throws Exception; } 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 c9ba172..5553d4c 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 @@ -7,6 +7,8 @@ import com.hfkj.entity.GoodsMsgExample; import com.hfkj.service.goods.GoodsMsgService; import org.apache.commons.collections4.MapUtils; import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Service; import javax.annotation.Resource; @@ -21,6 +23,9 @@ public class GoodsMsgServiceImpl implements GoodsMsgService { @Resource private GoodsMsgMapper goodsMsgMapper; + @Autowired + private RedisTemplate redisTemplate; + @Override public void create(GoodsMsg goodsMsg) { goodsMsgMapper.insert(goodsMsg); @@ -96,12 +101,27 @@ public class GoodsMsgServiceImpl implements GoodsMsgService { } @Override - public void addSaleNum(Long goodsId, Integer num) { + public void addSaleNum(Long goodsId, Integer num) throws Exception { + + String key = "GOODS" + goodsId; + + // 分布式锁占坑 + Boolean lock = redisTemplate.opsForValue().setIfAbsent(key, goodsId); + GoodsMsg goodsMsg = queryDetail(goodsId); if (goodsMsg != null) { - goodsMsg.setSaleNum(goodsMsg.getSaleNum() + num); - update(goodsMsg); + + if(Boolean.TRUE.equals(lock)) { + goodsMsg.setSaleNum(goodsMsg.getSaleNum() + num); + update(goodsMsg); + } else { + // 加锁失败,重试 + Thread.sleep(100); + addSaleNum(goodsId , num); + } + + } }