@Resource
private Redisson redisson;
@Resource
private StringRedisTemplate stringRedisTemplate;
/**
* 秒杀订单
* @return
*/
@RequestMapping("/test")
public String redisTest() {
String locKey = "locKey";
//String clientId = UUID.randomUUID().toString();
RLock redissonLock = redisson.getLock(locKey);
try {
//Boolean ifAbsent = stringRedisTemplate.opsForValue().setIfAbsent(locKey, "key");
//stringRedisTemplate.expire(locKey, 10, TimeUnit.SECONDS);
//设置锁,类似jedis.setnx(k,v),并设置超时时间防止死锁
// Boolean ifAbsent = stringRedisTemplate.opsForValue().setIfAbsent(locKey, clientId, 30, TimeUnit.SECONDS);
// if (!ifAbsent){
// return "wait···";
// }
//加锁
redissonLock.lock();
int parseInt = Integer.parseInt(stringRedisTemplate.opsForValue().get("orders"));
if (parseInt > 0 ){
int newParseInt = parseInt - 1;
stringRedisTemplate.opsForValue().set("orders", newParseInt + "");
System.out.println("订单扣减成功,剩余 == " + newParseInt);
}else {
System.out.println("库存不足");
}
return "success ···";
}finally {
//释放锁
redissonLock.unlock();
// if (clientId.equals(stringRedisTemplate.opsForValue().get(locKey))){
// stringRedisTemplate.delete(locKey);//删除锁
// }
}
}
redis分布式锁使用 例子
最新推荐文章于 2024-07-04 19:26:06 发布