Redis实现分布式锁最全讲解

在分布式架构中,为了实现一些业务,如控制产品超卖,我们需要某段代码是一个线程一个线程依次执行,这个时候单体架构下的synchronized 由于只在一个jvm中有效,这个时候就可以用到redis分布式锁来实现

首先实现一段库存扣减的代码:

package com.qingnian.spring.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class InventoryDeduction {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @RequestMapping("/reduce")
    @ResponseBody
    public String reduceDeduction(){
        //从redis内存中取出库存的总数
        int totalDeduction =Integer.valueOf(redisTemplate.opsForValue().get("totalDeduction"));
        if(totalDeduction>0){
            //库存存在,进行扣减操作
            totalDeduction-=1;
            System.out.println("扣减操作成功,剩余库存为===>"+totalDeduction);
            redisTemplate.opsForValue().set("totalDeduction", totalDeduction+"");
        }else{
            System.out.println("扣减操作失败");
        }
        return totalDeduction+"";
    }
}

redis 分布式锁 实现库存扣减

@Controller
public class InventoryDeduction {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @RequestMapping("/reduce")
    @ResponseBody
    public String reduceDeduction(){
        //redis锁
        /*此处利用redis单线程的特性,利用setNx()方法实现:如果多线程同时到达,只能有一个线程执行,
        如果key值存在,就等待,key值不存在,就设置对应的value,方法的返回类型是一个boolean值,true
        表示获得锁成功,false表示获取锁失败*/
        Boolean ifAbsent = redisTemplate.opsForValue().setIfAbsent("key", "value");
        if (!ifAbsent) {
            //获取锁失败
            return "请稍后重试";
        }
        int totalDeduction;
        //将业务执行部分放入try catch finall 语句中,如果出现异常,则在finall 释放掉当前锁,避免阻塞
        try {
            //从redis内存中取出库存的总数
            totalDeduction = Integer.valueOf(redisTemplate.opsForValue().get("totalDeduction"));
            if(totalDeduction>0){
                //库存存在,进行扣减操作
                totalDeduction-=1;
                System.out.println("扣减操作成功,剩余库存为===>"+totalDeduction);
                redisTemplate.opsForValue().set("totalDeduction", totalDeduction+"");
            }else{
                System.out.println("扣减操作失败");
            }
        } finally {
            redisTemplate.delete("key");
        }
        return totalDeduction+"";
    }
}

上方解决方案中有一个问题:如果执行业务过程中出了问题,非抛异常,当前线程的锁也会无法释放

解决方案:为锁设置过期时间,时间到了,锁自定失效

@Controller
public class InventoryDeduction {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @RequestMapping("/reduce")
    @ResponseBody
    public String reduceDeduction(){
        //redis锁
        /*此处利用redis单线程的特性,利用setNx()方法实现:如果多线程同时到达,只能有一个线程执行,
        如果key值存在,就等待,key值不存在,就设置对应的value,方法的返回类型是一个boolean值,true
        表示获得锁成功,false表示获取锁失败*/
        String lockKey="key";
        Boolean ifAbsent = redisTemplate.opsForValue().setIfAbsent(lockKey, "value");
        //设置锁的过期时间,时间一到,锁自动失效,下一个线程可获得锁
        redisTemplate.expire(lockKey,30, TimeUnit.SECONDS);
        if (!ifAbsent) {
            //获取锁失败
            return "请稍后重试";
        }
        int totalDeduction;
        //将业务执行部分放入try catch finall 语句中,如果出现异常,则在finall 释放掉当前锁,避免阻塞
        try {
            //从redis内存中取出库存的总数
            totalDeduction = Integer.valueOf(redisTemplate.opsForValue().get("totalDeduction"));
            if(totalDeduction>0){
                //库存存在,进行扣减操作
                totalDeduction-=1;
                System.out.println("扣减操作成功,剩余库存为===>"+totalDeduction);
                redisTemplate.opsForValue().set("totalDeduction", totalDeduction+"");
            }else{
                System.out.println("扣减操作失败");
            }
        } finally {
            redisTemplate.delete("key");
        }
        return totalDeduction+"";
    }
}  

上方解决方案中有一个问题:在锁的有限时间,跟业务的执行时间作用下,可能会出现一个情况,当前线程在finnally 语句块中释放锁的时候,第一个redis锁已经过期,而第二个线程刚好拿到锁,造成第一个线程释放掉了第二个线程的锁,造成死锁状态

解决方案:为锁设置不同的 value 值。释放锁的时候,验证 value,相同则进行释放

public class InventoryDeduction {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @RequestMapping("/reduce")
    @ResponseBody
    public String reduceDeduction(){
        //redis锁
        /*此处利用redis单线程的特性,利用setNx()方法实现:如果多线程同时到达,只能有一个线程执行,
        如果key值存在,就等待,key值不存在,就设置对应的value,方法的返回类型是一个boolean值,true
        表示获得锁成功,false表示获取锁失败*/
        String lockKey="key";
        String lockValue= UUID.randomUUID().toString();
        Boolean ifAbsent = redisTemplate.opsForValue().setIfAbsent(lockKey, lockValue);
        //设置锁的过期时间,时间一到,锁自动失效,下一个线程可获得锁
        redisTemplate.expire(lockKey,30, TimeUnit.SECONDS);
        if (!ifAbsent) {
            //获取锁失败
            return "请稍后重试";
        }
        int totalDeduction;
        //将业务执行部分放入try catch finall 语句中,如果出现异常,则在finall 释放掉当前锁,避免阻塞
        try {
            //从redis内存中取出库存的总数
            totalDeduction = Integer.valueOf(redisTemplate.opsForValue().get("totalDeduction"));
            if(totalDeduction>0){
                //库存存在,进行扣减操作
                totalDeduction-=1;
                System.out.println("扣减操作成功,剩余库存为===>"+totalDeduction);
                redisTemplate.opsForValue().set("totalDeduction", totalDeduction+"");
            }else{
                System.out.println("扣减操作失败");
            }
        } finally {
            //比较value值,如果相等,表示为同一线程,进行锁的释放
            if(lockValue==(String) redisTemplate.opsForValue().get(lockKey)){
                redisTemplate.delete("key");
            }
        }
        return totalDeduction+"";
    }
}

上方解决方案中有一个问题:锁的设置key值,锁的有限时间设定为两步操作,不具备原子性

解决方案:将key值,与有效时间合并为一步

@Controller
public class InventoryDeduction {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @RequestMapping("/reduce")
    @ResponseBody
    public String reduceDeduction(){
        String lockKey="key";
        String lockValue= UUID.randomUUID().toString();
        //此两步合并,保证原子性
        /*Boolean ifAbsent = redisTemplate.opsForValue().setIfAbsent(lockKey, lockValue);
        //设置锁的过期时间,时间一到,锁自动失效,下一个线程可获得锁
        redisTemplate.expire(lockKey,30, TimeUnit.SECONDS);*/
        Boolean ifAbsent = redisTemplate.opsForValue().setIfAbsent(lockKey, lockValue,30, TimeUnit.SECONDS);
        if (!ifAbsent) {
            //获取锁失败
            return "请稍后重试";
        }
        int totalDeduction;
        //将业务执行部分放入try catch finall 语句中,如果出现异常,则在finall 释放掉当前锁,避免阻塞
        try {
            //从redis内存中取出库存的总数
            totalDeduction = Integer.valueOf(redisTemplate.opsForValue().get("totalDeduction"));
            if(totalDeduction>0){
                //库存存在,进行扣减操作
                totalDeduction-=1;
                System.out.println("扣减操作成功,剩余库存为===>"+totalDeduction);
                redisTemplate.opsForValue().set("totalDeduction", totalDeduction+"");
            }else{
                System.out.println("扣减操作失败");
            }
        } finally {
            //比较value值,如果相等,表示为同一线程,进行锁的释放
            if(lockValue==(String) redisTemplate.opsForValue().get(lockKey)){
                redisTemplate.delete("key");
            }
        }
        return totalDeduction+"";
    }
}

redis 锁这样实现就可以了,如果考虑安全性,这个版本还有一点:第一个线程执行过程中,锁的过期时间到了,多个线程同时执行业务部分,可能会出错

解决方案:使用redisson 实现分布式锁,原理大概为:在第一个线程拿到锁的同时,开启一个守护线程,不停的定时去延长锁的有效时长,直到这把锁释放

代码部分:
1:pom 引入 redisson 依赖

<dependency>
     <groupId>org.redisson</groupId>
     <artifactId>redisson</artifactId>
     <version>3.6.5</version>
</dependency>

2:生成redisson 对象

@SpringBootApplication
@MapperScan(basePackages = "com.qingnian.spring.dao")
public class SpringbootRedisApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootRedisApplication.class, args);
    }

    @Bean
    public Redisson getRedisson(){
        Config config = new Config();
        //单机模式
        config.useSingleServer().setAddress("redis://127.0.0.1:6379").setDatabase(0);
        return (Redisson) Redisson.create(config);
    }
}

3:代码部分

@Controller
public class InventoryDeduction {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private Redisson redisson;

    @RequestMapping("/reduce")
    @ResponseBody
    public String reduceDeduction(){
        String lockKey="key";
        int totalDeduction;
        //redisson 实现锁
        RLock lock = redisson.getLock(lockKey);
        //将业务执行部分放入try catch finall 语句中,如果出现异常,则在finall 释放掉当前锁,避免阻塞
        try {
            lock.tryLock();
            //从redis内存中取出库存的总数
            totalDeduction = Integer.valueOf(redisTemplate.opsForValue().get("totalDeduction"));
            if(totalDeduction>0){
                //库存存在,进行扣减操作
                totalDeduction-=1;
                System.out.println("扣减操作成功,剩余库存为===>"+totalDeduction);
                redisTemplate.opsForValue().set("totalDeduction", totalDeduction+"");
            }else{
                System.out.println("扣减操作失败");
            }
        } finally {
            lock.unlock();
        }
        return totalDeduction+"";
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值