高并发下的分布式锁
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
相关文章
- 高并发下的分布式锁
public String deductStrck() throws InterruptedException{ String lockKey = "product_001"; //用
- solr 的Admin界面
query 1.q(query):定义查询的原始输入字符串。多个条件用AND、OR连接。一定存在在字段前加+号,不存在时在字段前面加-号 ``` company_name:上海有限责任公司 AND
- 递归和分治思想
一、斐波那契数列 1 1 2 3 5 8 13 21 34 55 89 144 ...... 我们可以用数学函数来定义: |0,当n = 0 F(n) = |1,当n = 1
- 使用create-react-app快速搭建react环境
使用create-react-app快速搭建react环境 npm install create-react-app -g cd test_dir create-react-app demo_rea
- CentOS编译安装PHP7.1.21环境
0.安装一大堆必备的东西 先执行 yum install -y epel-release yum install -y libmcrypt-devel 再执行 yum -y install gcc
随机推荐
- 高并发下的分布式锁
public String deductStrck() throws InterruptedException{ String lockKey = "product_001"; //用
- solr 的Admin界面
query 1.q(query):定义查询的原始输入字符串。多个条件用AND、OR连接。一定存在在字段前加+号,不存在时在字段前面加-号 ``` company_name:上海有限责任公司 AND
- 递归和分治思想
一、斐波那契数列 1 1 2 3 5 8 13 21 34 55 89 144 ...... 我们可以用数学函数来定义: |0,当n = 0 F(n) = |1,当n = 1
- 使用create-react-app快速搭建react环境
使用create-react-app快速搭建react环境 npm install create-react-app -g cd test_dir create-react-app demo_rea
- CentOS编译安装PHP7.1.21环境
0.安装一大堆必备的东西 先执行 yum install -y epel-release yum install -y libmcrypt-devel 再执行 yum -y install gcc