[Redis] Redisson分布式锁原理及源码分析

目录

基于 Redis 的分布式锁

Redisson实现分布式锁

Redisson分布式锁原理图

RedissonLock实现分布式锁源码分析

RedissonLock构造方法

lock()加锁

获取锁

锁续命逻辑

tryLockInnerAsync加锁lua脚本分析

unlock()解锁


基于 Redis 的分布式锁

实现方式:

  • 使用 Redis 的 SETNX 命令(Set if Not Exists)来确保只有一个客户端可以成功创建一个锁键。使用 EXPIRE 命令设置键的过期时间,防止死锁。
  • 如果客户端成功设置了锁键,它就获得了锁;如果失败,则表示锁已被其他客户端占用。
  • 为了解决锁失效或客户端故障问题,可以使用 Redisson 或者实现 Redlock 算法来增强锁的可靠性。

优点: 性能高,易于实现。

缺点: Redis 单节点故障或网络分区可能导致锁的不一致性。

Redisson实现分布式锁

参考网站:目录 · redisson/redisson Wiki · GitHub

Redisson分布式锁原理图

RedissonLock实现分布式锁源码分析

代码示例

代码片段是一个用于扣减商品库存的简单示例,使用了Redisson作为分布式锁的实现,并且通过StringRedisTemplate与Redis进行交互。

public String deductStock() {
    String lockKey = "lock:product_101";// 定义分布式锁的名称,可以使用商品ID等唯一标识
    //Boolean result = stringRedisTemplate.opsForValue().setIfAbsent(lockKey, "test666");
    //stringRedisTemplate.expire(lockKey, 10, TimeUnit.SECONDS);
    /*String clientId = UUID.randomUUID().toString();
    Boolean result = stringRedisTemplate.opsForValue().setIfAbsent(lockKey, clientId, 30, TimeUnit.SECONDS); //jedis.setnx(k,v)
    if (!result) {
        return "error_code";
    }*/
    //获取锁对象
    RLock redissonLock = redisson.getLock(lockKey);
    //加分布式锁
    redissonLock.lock();  //  .setIfAbsent(lockKey, clientId, 30, TimeUnit.SECONDS);
    try {
        // 从Redis中获取当前库存,并将其解析为整数
        int stock = Integer.parseInt(stringRedisTemplate.opsForValue().get("stock")); // jedis.get("stock")
        if (stock > 0) {
            int realStock = stock - 1;
            // 更新库存值到Redis
            stringRedisTemplate.opsForValue().set("stock", realStock + ""); // jedis.set(key,value)
            System.out.println("扣减成功,剩余库存:" + realStock);
        } else {
            System.out.println("扣减失败,库存不足");
        }
    } finally {
        /*if (clientId.equals(stringRedisTemplate.opsForValue().get(lockKey))) {
            stringRedisTemplate.delete(lockKey);
        }*/
        //解锁
        redissonLock.unlock();
    }
    return "end";
}

RedissonLock构造方法

public RedissonLock(CommandAsyncExecutor commandExecutor, String name) {
    // 调用父类构造函数,传递命令执行器和锁的名称
    super(commandExecutor, name);
    // 将传入的命令执行器赋值给当前对象的commandExecutor字段
    this.commandExecutor = commandExecutor;
    // 从连接管理器获取当前实例的唯一标识符并赋值给id字段,UUID.randomUUID()生成
    this.id = commandExecutor.getConnectionManager().getId();
    // 从连接管理器的配置中获取锁看门狗超时时间(默认30s),并赋值给internalLockLeaseTime字段
    this.internalLockLeaseTime = commandExecutor.getConnectionManager().getCfg().getLockWatchdogTimeout();
}

lock()加锁

//获取锁对象
RLock redissonLock = redisson.getLock(lockKey);
//加分布式锁
redissonLock.lock(); 
@Override
public void lock() {
    try {
        // 调用可中断的锁获取方法
        lockInterruptibly();
    } catch (InterruptedException e) {
        // 恢复线程的中断状态
        Thread.currentThread().interrupt();
    }
}
@Override
public void lockInterruptibly() throws InterruptedException {
    // 调用可中断的锁获取方法,不设置超时时间
    lockInterruptibly(-1, null);
}

获取锁

消息订阅使用到了信号量Semaphore获取许可,如果锁未获取成功,使用while进行循环获取锁,如果还没获取到锁,就会进行阻塞,阻塞时间到或者收到订阅的锁释放的消息就会继续获取锁。

@Override
public void lockInterruptibly(long leaseTime, TimeUnit unit) throws InterruptedException {
    // 获取当前线程的ID
    long threadId = Thread.currentThread().getId();

    // 尝试获取锁并返回剩余的超时时间
    Long ttl = tryAcquire(leaseTime, unit, threadId);

    // 如果成功获取锁(ttl为null表示成功)
    if (ttl == null) {
        return; // 返回,锁已被获取
    }

    // 订阅锁释放的消息,使用到了信号量Semaphore
    RFuture<RedissonLockEntry> future = subscribe(threadId);
    commandExecutor.syncSubscription(future);

    try {
        while (true) {
            // 再次尝试获取锁
            ttl = tryAcquire(leaseTime, unit, threadId);

            // 如果成功获取锁(ttl为null表示成功)
            if (ttl == null) {
                break; // 退出循环,锁已被获取
            }

            // 如果ttl大于等于0,等待消息通知
            if (ttl >= 0) {
                // 阻塞ttl时间,让出cpu,避免占用资源
                // 或者接受到订阅消息唤醒,会继续获取锁
                getEntry(threadId).getLatch().tryAcquire(ttl, TimeUnit.MILLISECONDS);
            } else {
                // 如果ttl小于0,一直等待消息通知
                getEntry(threadId).getLatch().acquire();
            }
        }
    } finally {
        // 取消订阅锁释放的消息
        unsubscribe(future, threadId);
    }
//        get(lockAsync(leaseTime, unit));
}
private Long tryAcquire(long leaseTime, TimeUnit unit, long threadId) {
    // 调用 tryAcquireAsync 方法异步尝试获取锁,并等待结果
    return get(tryAcquireAsync(leaseTime, unit, threadId));
}

锁续命逻辑

在持有锁的剩余过期时间快使用完,而任务还未执行完成就会刷新锁的过期时间,启动续锁任务,定期刷新锁的过期时间。

private <T> RFuture<Long> tryAcquireAsync(long leaseTime, TimeUnit unit, final long threadId) {
    // 如果超时时间不等于-1,表示设置了时间
    if (leaseTime != -1) {
        // 调用 tryLockInnerAsync 方法来尝试获取锁,并返回剩余的超时时间
        return tryLockInnerAsync(leaseTime, unit, threadId, RedisCommands.EVAL_LONG);
    }

    // 如果超时时间等于-1,表示未设置时间
    // 使用锁看门狗超时时间作为默认超时时间
    RFuture<Long> ttlRemainingFuture = tryLockInnerAsync(commandExecutor.getConnectionManager().getCfg().getLockWatchdogTimeout(), TimeUnit.MILLISECONDS, threadId, RedisCommands.EVAL_LONG);
    
    // 添加监听器,用于处理锁的获取结果
    ttlRemainingFuture.addListener(new FutureListener<Long>() {
        @Override
        public void operationComplete(Future<Long> future) throws Exception {
            if (!future.isSuccess()) {
                return;
            }

            Long ttlRemaining = future.getNow();
            
            // 如果成功获取锁(ttlRemaining为null表示成功)
            if (ttlRemaining == null) {
                // 启动续锁任务,定期刷新锁的过期时间,
                scheduleExpirationRenewal(threadId);
            }
        }
    });
    
    // 返回包含锁的剩余超时时间的Future
    return ttlRemainingFuture;
}

tryLockInnerAsync加锁lua脚本分析

<T> RFuture<T> tryLockInnerAsync(long leaseTime, TimeUnit unit, long threadId, RedisStrictCommand<T> command) {
    // 计算超时时间的毫秒表示
    internalLockLeaseTime = unit.toMillis(leaseTime);

    // 使用Redis的EVAL命令执行一段Lua脚本,尝试获取锁
    return commandExecutor.evalWriteAsync(getName(), LongCodec.INSTANCE, command,
        "if (redis.call('exists', KEYS[1]) == 0) then " + 				//如果锁不存在
            // 使用HSET命令将锁信息存储到Redis哈希表中
            "redis.call('hset', KEYS[1], ARGV[2], 1); " +
            // 设置锁的过期时间(默认30毫秒)
            "redis.call('pexpire', KEYS[1], ARGV[1]); " +
            // 返回nil表示成功获取锁,对应java的null
            "return nil; " +
        "end; " +
        "if (redis.call('hexists', KEYS[1], ARGV[2]) == 1) then " +		// 如果锁已存在
            // 表示当前线程已经持有锁,可重入锁,增加锁的计数
            "redis.call('hincrby', KEYS[1], ARGV[2], 1); " +
            // 设置锁的过期时间(毫秒)
            "redis.call('pexpire', KEYS[1], ARGV[1]); " +
            // 返回nil表示成功获取锁
            "return nil; " +
        "end; " +
        // 如果锁已被其他线程持有,返回锁的剩余过期时间
        "return redis.call('pttl', KEYS[1]);",
        // getName()对应KEYS[1]、internalLockLeaseTime对应ARGV[1]、threadId对应ARGV[2]
        Collections.<Object>singletonList(getName()), internalLockLeaseTime, getLockName(threadId));
}

加锁成功后,创建并调度锁的过期锁续命任务,每间隔10s执行一次。通过执行 Lua 脚本,判断锁是否仍然有效,并更新锁的过期时间为30s。如果续约成功,则再次调度续约任务。

private void scheduleExpirationRenewal(final long threadId) {
    // 检查是否已经存在该锁的过期续约任务,如果存在则直接返回,避免重复创建任务
    if (expirationRenewalMap.containsKey(getEntryName())) {
        return;
    }

    // 创建一个定时任务
    Timeout task = commandExecutor.getConnectionManager().newTimeout(new TimerTask() {
        @Override
        public void run(Timeout timeout) throws Exception {
            // 通过执行Lua脚本进行过期时间的续约
            RFuture<Boolean> future = commandExecutor.evalWriteAsync(getName(), LongCodec.INSTANCE, RedisCommands.EVAL_BOOLEAN,
                    "if (redis.call('hexists', KEYS[1], ARGV[2]) == 1) then " +//锁存在
                        // 设置锁的过期时间(默认30毫秒)
                        "redis.call('pexpire', KEYS[1], ARGV[1]); " +
                        "return 1; " +
                    "end; " +
                    "return 0;",
                      Collections.<Object>singletonList(getName()), internalLockLeaseTime, getLockName(threadId));
             // 添加监听器,处理续约结果
            future.addListener(new FutureListener<Boolean>() {
                @Override
                public void operationComplete(Future<Boolean> future) throws Exception {
                    expirationRenewalMap.remove(getEntryName());// 续约完成后从续约任务列表中移除当前锁的标识
                    if (!future.isSuccess()) {// 续约失败,打印错误日志
                        log.error("Can't update lock " + getName() + " expiration", future.cause());
                        return;
                    }
                    
                    if (future.getNow()) {
                        // reschedule itself// 续约成功后再次调度续约任务
                        scheduleExpirationRenewal(threadId);
                    }
                }
            });
        }
        //默认为30秒,30/3=10秒
    }, internalLockLeaseTime / 3, TimeUnit.MILLISECONDS);
	// 将当前锁的标识和续约任务放入续约任务列表,如果之前已经存在该锁的续约任务,则取消之前的任务
    if (expirationRenewalMap.putIfAbsent(getEntryName(), task) != null) {
        task.cancel();
    }
}

unlock()解锁

@Override
public void unlock() {
    // 调用异步解锁方法,传递当前线程的ID,并等待异步操作的结果
    Boolean opStatus = get(unlockInnerAsync(Thread.currentThread().getId()));
    // 如果异步解锁操作返回的状态为null,说明当前线程并没有持有锁,抛出异常
    if (opStatus == null) {
        throw new IllegalMonitorStateException("尝试解锁,但当前线程未持有该锁,节点ID: "
                + id + " 线程ID: " + Thread.currentThread().getId());
    }
    // 如果解锁操作成功(返回值为true),则取消锁的自动续期(看门狗机制)
    if (opStatus) {
        cancelExpirationRenewal();
    }
}
protected RFuture<Boolean> unlockInnerAsync(long threadId) {
    return commandExecutor.evalWriteAsync(getName(), LongCodec.INSTANCE, RedisCommands.EVAL_BOOLEAN,
            "if (redis.call('exists', KEYS[1]) == 0) then " + //锁不存在
                "redis.call('publish', KEYS[2], ARGV[1]); " +//发布锁释放的消息
                "return 1; " +// 返回1,表示锁已经释放
            "end;" +
            "if (redis.call('hexists', KEYS[1], ARGV[3]) == 0) then " +//已经释放锁
                "return nil;" +
            "end; " +
            "local counter = redis.call('hincrby', KEYS[1], ARGV[3], -1); " + //设置为-1,之前是1
            "if (counter > 0) then " +
                "redis.call('pexpire', KEYS[1], ARGV[2]); " +//可重入锁
                "return 0; " +
            "else " +
                // 释放锁、发布信息
                "redis.call('del', KEYS[1]); " +
                "redis.call('publish', KEYS[2], ARGV[1]); " +
                "return 1; "+// 返回1,表示锁已经释放
            "end; " +
            "return nil;",
            Arrays.<Object>asList(getName(), getChannelName()), LockPubSub.unlockMessage, internalLockLeaseTime, getLockName(threadId));
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值