赞
踩
public class RedisLockController {
private static final Logger LOGGER = LoggerFactory.getLogger(RedisLockController.class);
@Resource
private StringRedisTemplate stringRedisTemplate;
@RequestMapping(“/deduct_stock”)
@Transactional
public ApiResult deductStock() {
String lockKey = “lockKey”;
String clientId = UUID.randomUUID().toString();
try {
Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(lockKey, clientId, 30, TimeUnit.SECONDS);
if (!flag) return new ApiResult(ReturnEnum.FAILED, “Not the same lock”);
int stockNum = Integer.parseInt(stringRedisTemplate.opsForValue().get(“stock”));
if (stockNum > 0) {
int realStockNum = stockNum - 1;
stringRedisTemplate.opsForValue().set(“stock”, realStockNum + “”);
LOGGER.info(“扣减成功,剩余库存:{}”, realStockNum);
} else
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。