底层用的redis的setNX,利用它的唯一性来确保只有一个key;
//创建一个key 如果有这个key hasLock返回true 否则返回false
Boolean hasLock = stringRedisTemplate.opsForValue().setIfAbsent("myLock", "999");
stringRedisTemplate.expire("myLock", 10, TimeUnit.SECONDS);
//把全部商品信息放进redis中
storeService.check();
//如果true
if (hasLock) {
try {
String maota = stringRedisTemplate.opsForValue().get("store:1");
Long maotao = Long.valueOf(maota);
if (maotao > 0) {
maotao = stringRedisTemplate.opsForValue().decrement("store:1");
log.debug("售出茅台一瓶,还剩:{}瓶", maotao);
new Thread(()->storeService.updateByBookId(1,1));
return HttpResp.success("去库存成功");
}
} finally {
//成功与否都删除key
stringRedisTemplate.delete("myLock");
log.debug("释放分布式锁成功");
}
}
log.debug("去库存失败");
return HttpResp.failed("去库存失败");
}