redis 特性
redis 是单线程的,NIO的异步的 (redis 会把并发的请求排队)
SETNX实现分布式锁 incr
1.手动实现简单的分布式锁
@RequestMapping(value = "/testStock", method = RequestMethod.GET)
public void testStock(){
long num = redisTemplate.opsForValue().increment("lock", 1);
if(num ==1){
Object obj = redisTemplate.opsForValue().get("stock");
long stock = FeatureDefult.getObject2Long(obj);
if(stock>0){
redisTemplate.opsForValue().set("stock", stock-1);
System.out.println("操作成功!操作之后的库存数为:"+(stock-1));
}
}else{
System.out.println("库存不足");
}
redisTemplate.opsForValue().increment("lock", -1);
}
考虑到异常问题,对代码做改进
@RequestMapping(value = "/reduceStock", method = RequestMethod.GET)
public void reduceStock(){
try {
long num = redisTemplate.opsForValue().increment("lock", 1);
redisTemplate.expire("lock", 10, TimeUnit.SECONDS);
if(num ==1){
Object obj = redisTemplate.opsForValue().get("stock");
long stock = FeatureDefult.getObject2Long(obj);
if(stock>0){
redisTemplate.opsForValue().set("stock", stock-1);
System.out.println("操作成功!操作之后的库存数为:"+(stock-1));
}
}else{
System.out.println("库存不足");
}
} finally {
redisTemplate.opsForValue().increment("lock", -1);
}
}
常用 redisson 框架帮助我们更好的实现 redis 分布式锁