高并发下的分布式锁
public String deductStrck() throws InterruptedException{
String lockKey = "product_001"; //用作一把分布式锁
String clientId = UUID.randomUUID().toString(); //记录锁的id,防止别的线程可以解开这把锁
try{
//开始锁住
//设置超时时间目的是为了防止程序突然中断而造成的死锁现象
//锁的续命操作:时间设置为10,可以再开一个线程每3分钟检查一下看看这把锁是否存在,如果存在将过期时间再延长
Boolean result = stringRedisTemplate.opsForValue().setIfAbsent(lockKey,clientId,10,TimeUnit.SECONDS)
if(!result){
return error;
}
//业务逻辑
int stock Integer.parseInt(stringRedisTemplate.opsForValue().get("stock"));
if(stock>0){
int realStock = stock-1;
stringRedisTemplate.opsForValue().set("stock",realStock);
System.out.println("扣减成功,剩余库存"+realStock);
}else{
System.out.println("扣减失败,库存不足");
}
}finally{//最终要解开这把锁
if(clientId.equals(stringRedisTemplate.opsForValue().get(lockKey))){//防止别的线程可以解开这把锁
stringRedisTemplate.opsForValue().deleted(lockKey);
}
}
}
redisson提供完善的分布式锁:https://redisson.org
相关文章
- redis 运维常用命令
time #查看时间戳与微妙数 dbsize #查看当前数据库中key数量 bgrewriteaof #后台进程重写aof bgsave #后台保存rdb快照 save #保存rd
- 使用create-react-app快速搭建react环境
使用create-react-app快速搭建react环境 npm install create-react-app -g cd test_dir create-react-app demo_rea
- php手动编译fileinfo扩展
某些同学在执行php composer.phar install时,出现错误 90%可能是漏装了PHP的fileinfo扩展了,用宝塔的请直接在宝塔里安装 下载并解压PHP源码包(内含fileinfo
- 路由器
- 递归和分治思想
一、斐波那契数列 1 1 2 3 5 8 13 21 34 55 89 144 ...... 我们可以用数学函数来定义: |0,当n = 0 F(n) = |1,当n = 1
随机推荐
- redis 运维常用命令
time #查看时间戳与微妙数 dbsize #查看当前数据库中key数量 bgrewriteaof #后台进程重写aof bgsave #后台保存rdb快照 save #保存rd
- 使用create-react-app快速搭建react环境
使用create-react-app快速搭建react环境 npm install create-react-app -g cd test_dir create-react-app demo_rea
- php手动编译fileinfo扩展
某些同学在执行php composer.phar install时,出现错误 90%可能是漏装了PHP的fileinfo扩展了,用宝塔的请直接在宝塔里安装 下载并解压PHP源码包(内含fileinfo
- 路由器
- 递归和分治思想
一、斐波那契数列 1 1 2 3 5 8 13 21 34 55 89 144 ...... 我们可以用数学函数来定义: |0,当n = 0 F(n) = |1,当n = 1