@Autowired
private StringRedisTemplate stringRedisTemplate;
@GetMapping("test1")
public String test(){
String lockKey="product_10";
String clientId= UUID.randomUUID().toString();
//设置分布式锁
boolean result=stringRedisTemplate.opsForValue().setIfAbsent(lockKey,clientId);
stringRedisTemplate.expire(lockKey,10, TimeUnit.SECONDS);//设置超时时间
if(!result){
return "error_code";
}
try {
int stock = Integer.parseInt(stringRedisTemplate.opsForValue().get("cms:stock"));
if (stock > 0) {
int realStock = stock - 1;
stringRedisTemplate.opsForValue().set("cms:stock", realStock + "");
System.out.println("减扣成功,剩余库存:" + realStock);
} else {
System.out.println("减扣失败,库存不足");
}
}finally {
//是自己加的锁才可以删除 不可以删除别人的锁
if(clientId.equals(stringRedisTemplate.opsForValue().get(lockKey))){
stringRedisTemplate.delete(lockKey);
}
}
return "success";
}