master
袁野 6 months ago
parent 01a4c47220
commit 7a428eee6b
  1. 2
      service/src/main/java/com/hfkj/service/goods/GoodsMsgService.java
  2. 22
      service/src/main/java/com/hfkj/service/goods/impl/GoodsMsgServiceImpl.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;
}

@ -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) {
if(Boolean.TRUE.equals(lock)) {
goodsMsg.setSaleNum(goodsMsg.getSaleNum() + num);
update(goodsMsg);
} else {
// 加锁失败,重试
Thread.sleep(100);
addSaleNum(goodsId , num);
}
}
}

Loading…
Cancel
Save