高并发下的分布式锁
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
相关文章
- php手动编译fileinfo扩展
某些同学在执行php composer.phar install时,出现错误 90%可能是漏装了PHP的fileinfo扩展了,用宝塔的请直接在宝塔里安装 下载并解压PHP源码包(内含fileinfo
- 常见排序列表
常见排序列表 中文名称 英文名称 平均时间复杂度 最坏时间复杂度 最好时间复杂度 空间复杂度 稳定性 选择排序 Selection n^2 n^2 n^2 1 不稳 冒泡排序 Bub
- 高并发下的分布式锁
public String deductStrck() throws InterruptedException{ String lockKey = "product_001"; //用
- redis的过期策略以及内存淘汰机制
一、分析 这个问题其实相当重要,到底redis有没用到家,这个问题就可以看出来。比如你redis只能存5G数据,可是你写了10G,那会删5G的数据。怎么删的,这个问题思考过么?还有,你的数据已经设置
- 使用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
- 常见排序列表
常见排序列表 中文名称 英文名称 平均时间复杂度 最坏时间复杂度 最好时间复杂度 空间复杂度 稳定性 选择排序 Selection n^2 n^2 n^2 1 不稳 冒泡排序 Bub
- 高并发下的分布式锁
public String deductStrck() throws InterruptedException{ String lockKey = "product_001"; //用
- redis的过期策略以及内存淘汰机制
一、分析 这个问题其实相当重要,到底redis有没用到家,这个问题就可以看出来。比如你redis只能存5G数据,可是你写了10G,那会删5G的数据。怎么删的,这个问题思考过么?还有,你的数据已经设置
- 使用create-react-app快速搭建react环境
使用create-react-app快速搭建react环境 npm install create-react-app -g cd test_dir create-react-app demo_rea