redisson锁相关源码

1、redisson加锁源码理解

​   redisson先获取RLock对象,调用lock、tryLock方法来完成加锁的功能

​   lock方法是直接加锁,如果锁已被占用,则直接线程阻塞,进行等待,直到锁被占用方释放。

  tryLock方法则是设定了waitTime(等待时间),在这个等待时间没到前,也是线程阻塞并反复去获取锁,直到取到锁或等待时间超时,则返回false


2、加锁

   1、LOCK加锁

/**
 * 加锁操作 (设置锁的有效时间)
 * @param lockName 锁名称
 * @param leaseTime  锁有效时间
 */
public void lock(String lockName, long leaseTime) {
    RLock rLock = redisson.getLock(lockName);
    rLock.lock(leaseTime, TimeUnit.SECONDS);
}

  这一步主要分为了俩种方式,第一种是外部传递进来了锁的释放时间,第二种是直接一定在等待(-1)锁的释放时间

@Override
public void lock(long leaseTime, TimeUnit unit) {
    try {
        lockInterruptibly(leaseTime, unit);
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    }
}
@Override
public void lockInterruptibly() throws InterruptedException {
    lockInterruptibly(-1, null);
}
 @Override
public void lockInterruptibly(long leaseTime, TimeUnit unit) throws InterruptedException {
	//获取当前线程ID
    long threadId = Thread.currentThread().getId();
    //去获取锁,如果没有获取到这个ttl是等于空,如果没有获取到锁这个TTL就是这个锁还有多长时间
    Long ttl = tryAcquire(leaseTime, unit, threadId);
    // lock acquired
    if (ttl == null) {
    	//加锁成功
         return;
    }

	//这是开始订阅事件,比如现在另外一个线程进来,但是发现锁已经被前面的线程已经获取到了,那么当前线程通过 Redis 的 channel 订阅锁释放的事件
    RFuture<RedissonLockEntry> future = subscribe(threadId);
    //命令模式进行同步订阅事件
    commandExecutor.syncSubscription(future);

    try {
    	//进入死循环,等待获取锁的进程并不是通过一个 while(true) 死循环去获取锁,而是利用了 Redis 的发布订阅机制,通过 await 方法阻塞等待锁的进程,有效的解决了无效的锁申请浪费资源的问题 (Semaphore)
        while (true) {
        	//重新去获取锁
           ttl = tryAcquire(leaseTime, unit, threadId);
           // lock acquired
           if (ttl == null) {
	           //加锁成功
               break;
           }

            // waiting for message
            //阻塞等待锁(通过信号量(共享锁)阻塞,等待解锁消息)当锁释放并发布释放锁的消息后,
            信号量的 release() 方法会被调用,此时被信号量阻塞的等待队列中的一个线程就可以继续尝试获取锁了
            if (ttl >= 0) {
            	//如果TTL>=0 则重新去信号量重试去获取信息
                 getEntry(threadId).getLatch().tryAcquire(ttl, TimeUnit.MILLISECONDS);
            } else {
            	 //如果小于0则进行等待获取信息
                  getEntry(threadId).getLatch().acquire();
            }
         }
    } finally {
    	//无论是否获得锁,都要取消订阅解锁消息
         unsubscribe(future, threadId);
    }
//     get(lockAsync(leaseTime, unit));
    }
//获取锁的逻辑其实就是通过一段lua脚本实现
<T> RFuture<T> tryLockInnerAsync(long leaseTime, TimeUnit unit, long threadId, RedisStrictCommand<T> command) {
    internalLockLeaseTime = unit.toMillis(leaseTime);

    return commandExecutor.evalWriteAsync(getName(), LongCodec.INSTANCE, command,
              "if (redis.call('exists', KEYS[1]) == 0) then " +
                  "redis.call('hset', KEYS[1], ARGV[2], 1); " +
                  "redis.call('pexpire', KEYS[1], ARGV[1]); " +
                  "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]); " +
                  "return nil; " +
              "end; " +
              "return redis.call('pttl', KEYS[1]);",
                Collections.<Object>singletonList(getName()), internalLockLeaseTime, getLockName(threadId));
}

这里进行加锁了,默认keys[1] =加锁的key 、ARGV[1]=30秒(internalLockLeaseTime)、ARGV[2] 代表的是加锁的客户端的 ID、最后面的一个 1 是为了后面可重入做的计数统计,其实这里满足了

  1. 指定一个 key 作为锁标记,存入 Redis 中,指定一个 唯一的用户标识 作为 value。
  2. 当 key 不存在时才能设置值,确保同一时间只有一个客户端进程获得锁,满足 互斥性 特性。
  3. 设置一个过期时间,防止因系统异常导致没能删除这个 key,满足 防死锁 特性。
  4. 当处理完业务之后需要清除这个 key 来释放锁,清除 key 时需要校验 value 值,需要满足 只有加锁的人才能释放锁


   2、tryLock加锁

 public boolean tryLock(long waitTime, long leaseTime, TimeUnit unit) throws InterruptedException {
        long time = unit.toMillis(waitTime);
        long current = System.currentTimeMillis();
        long threadId = Thread.currentThread().getId();
        // 1.尝试获取锁
        Long ttl = tryAcquire(leaseTime, unit, threadId);
        // lock acquired
        if (ttl == null) {
            return true;
        }

        // 申请锁的耗时如果大于等于最大等待时间,则申请锁失败.
        time -= System.currentTimeMillis() - current;
        if (time <= 0) {
            acquireFailed(threadId);
            return false;
        }

        current = System.currentTimeMillis();

        /**
         * 2.订阅锁释放事件,并通过 await 方法阻塞等待锁释放,有效的解决了无效的锁申请浪费资源的问题:
         * 基于信息量,当锁被其它资源占用时,当前线程通过 Redis 的 channel 订阅锁的释放事件,一旦锁释放会发消息通知待等待的线程进行竞争.
         *
         * 当 this.await 返回 false,说明等待时间已经超出获取锁最大等待时间,取消订阅并返回获取锁失败.
         * 当 this.await 返回 true,进入循环尝试获取锁.
         */
        RFuture<RedissonLockEntry> subscribeFuture = subscribe(threadId);
        // await 方法内部是用 CountDownLatch 来实现阻塞,获取 subscribe 异步执行的结果(应用了 Netty 的 Future)
        if (!subscribeFuture.await(time, TimeUnit.MILLISECONDS)) {
            if (!subscribeFuture.cancel(false)) {
                subscribeFuture.onComplete((res, e) -> {
                    if (e == null) {
                        unsubscribe(subscribeFuture, threadId);
                    }
                });
            }
            acquireFailed(threadId);
            return false;
        }

        try {
            // 计算获取锁的总耗时,如果大于等于最大等待时间,则获取锁失败.
            time -= System.currentTimeMillis() - current;
            if (time <= 0) {
                acquireFailed(threadId);
                return false;

              }

            /**
             * 3.收到锁释放的信号后,在最大等待时间之内,循环一次接着一次的尝试获取锁
             * 获取锁成功,则立马返回 true,
             * 若在最大等待时间之内还没获取到锁,则认为获取锁失败,返回 false 结束循环
             */
            while (true) {
                long currentTime = System.currentTimeMillis();

                // 再次尝试获取锁
                ttl = tryAcquire(leaseTime, unit, threadId);
                // lock acquired
                if (ttl == null) {
                    return true;
                }
                // 超过最大等待时间则返回 false 结束循环,获取锁失败
                time -= System.currentTimeMillis() - currentTime;
                if (time <= 0) {
                    acquireFailed(threadId);
                    return false;
                }

                /**
                 * 6.阻塞等待锁(通过信号量(共享锁)阻塞,等待解锁消息):
                 */
                currentTime = System.currentTimeMillis();
                if (ttl >= 0 && ttl < time) {
                    //如果剩余时间(ttl)小于wait time ,就在 ttl 时间内,从Entry的信号量获取一个许可(除非被中断或者一直没有可用的许可)。
                    getEntry(threadId).getLatch().tryAcquire(ttl, TimeUnit.MILLISECONDS);
                } else {
                    //则就在wait time 时间范围内等待可以通过信号量
                    getEntry(threadId).getLatch().tryAcquire(time, TimeUnit.MILLISECONDS);
                }

                // 更新剩余的等待时间(最大等待时间-已经消耗的阻塞时间)
                time -= System.currentTimeMillis() - currentTime;
                if (time <= 0) {
                    acquireFailed(threadId);
                    return false;
                }
            }
        } finally {
            // 7.无论是否获得锁,都要取消订阅解锁消息
            unsubscribe(subscribeFuture, threadId);
        }
//        return get(tryLockAsync(waitTime, leaseTime, unit));
    }

3、锁互斥机制

​   以上加锁的逻辑,此时,如果客户端 2 来尝试加锁,会如何呢?首先,第一个 if 判断会执行 exists KEYS[1] 这个锁 key 已经存在了。接着第二个 if 判断,判断一下,myLock 锁 key 的 hash 数据结构中,是否包含客户端 2 的 ID,这里明显不是,因为那里包含的是客户端 1 的 ID。所以,客户端 2 会执行:

return redis.call('pttl', KEYS[1]);

这里会返回的一个数字,这个数字代表了KEYS[1] 这个锁 key 的剩余生存时间


4、锁的续签

​    Long ttl = tryAcquire(leaseTime, unit, threadId);

private Long tryAcquire(long leaseTime, TimeUnit unit, long threadId) {
    return get(tryAcquireAsync(leaseTime, unit, threadId));
}
private <T> RFuture<Long> tryAcquireAsync(long leaseTime, TimeUnit unit, final long threadId) {
    //判断失效时间是不是等于-1,如果不等于-1就是会调用tryLock等待锁的方法
    if (leaseTime != -1) {
        return tryLockInnerAsync(leaseTime, unit, threadId, RedisCommands.EVAL_LONG);
    }
    
    //当失效时间等于-1的时候就会开启一个Watchdog机制,以为默认-1的锁失效时间是30秒钟(private long lockWatchdogTimeout = 30 * 1000),如果是自定义时间的话,流程就不会走到这里
    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();
            // lock acquired
            if (ttlRemaining == null) {
                scheduleExpirationRenewal(threadId);
            }
        }
    });
    return ttlRemainingFuture;
}
private void scheduleExpirationRenewal(final long threadId) {
	//判断失效锁中的Map是否持有锁 key
    if (expirationRenewalMap.containsKey(getEntryName())) {
        return;
    }

	//开启一个定时任务,每10秒钟执行一次续签internalLockLeaseTime=(private long lockWatchdogTimeout = 30 * 1000)
    Timeout task = commandExecutor.getConnectionManager().newTimeout(new TimerTask() {
        @Override
        public void run(Timeout timeout) throws Exception {
             // 这个操作会将key的过期时间重新设置为30
            RFuture<Boolean> future = commandExecutor.evalWriteAsync(getName(), LongCodec.INSTANCE, RedisCommands.EVAL_BOOLEAN,
                    "if (redis.call('hexists', KEYS[1], ARGV[2]) == 1) then " +
                        "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);
                    }
                }
            });
        }
    }, internalLockLeaseTime / 3, TimeUnit.MILLISECONDS);

	//如果锁已经没有,就不需要进行重新调用了
    if (expirationRenewalMap.putIfAbsent(getEntryName(), task) != null) {
        task.cancel();
    }
}

  Watch Dog 机制其实就是一个后台定时任务线程,获取锁成功之后,会将持有锁的线程放入到一个 RedissonLock.EXPIRATION_RENEWAL_MAP里面,然后每隔 10 秒 (internalLockLeaseTime / 3) 检查一下,如果客户端 1 还持有锁 key(判断客户端是否还持有 key,其实就是遍历 EXPIRATION_RENEWAL_MAP 里面线程 id 然后根据线程 id 去 Redis 中查,如果存在就会延长 key 的时间),那么就会不断的延长锁 key 的生存时间。

注意:这里有一个细节问题,如果服务宕机了,Watch Dog 机制线程也就没有了,此时就不会延长 key 的过期时间,到了 30s 之后就会自动过期了,其他线程就可以获取到锁


5、公平锁

​   具体参考:https://www.cnblogs.com/wang-meng/p/12530762.html


6、联锁

   1、什么是联锁

​     基于Redis的Redisson分布式联锁RedissonMultiLock对象可以将多个RLock对象关联为一个联锁,每个RLock对象实例可以来自于不同的Redisson实例


   2、源码

RLock lock1 = redissonInstance1.getLock("lock1"); 
RLock lock2 = redissonInstance2.getLock("lock2"); 
RLock lock3 = redissonInstance3.getLock("lock3"); 
RedissonMultiLock lock = new RedissonMultiLock(lock1, lock2, lock3); 
// 同时加锁:lock1 lock2 lock3 
// 所有的锁都上锁成功才算成功。 
 lock.lock(); ... 
 lock.unlock();
public void lock(long leaseTime, TimeUnit unit) {
    try {
        lockInterruptibly(leaseTime, unit);
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    }
}

@Override
public void lockInterruptibly() throws InterruptedException {
    lockInterruptibly(-1, null);
}

public void lockInterruptibly(long leaseTime, TimeUnit unit) throws InterruptedException {
    long waitTime = -1;
    //判断失效时间重新赋值等待时间
    if (leaseTime == -1) {
        waitTime = 5;
        unit = TimeUnit.SECONDS;
    } else {
        waitTime = unit.toMillis(leaseTime);
        if (waitTime <= 2000) {
            waitTime = 2000;
        } else if (waitTime <= 5000) {
            waitTime = ThreadLocalRandom.current().nextLong(waitTime/2, waitTime);
        } else {
            waitTime = ThreadLocalRandom.current().nextLong(5000, waitTime);
        }
        waitTime = unit.convert(waitTime, TimeUnit.MILLISECONDS);
    }
    
    //循环去获取锁
    while (true) {
        if (tryLock(waitTime, leaseTime, unit)) {
            return;
        }
    }
}
public boolean tryLock(long waitTime, long leaseTime, TimeUnit unit) throws InterruptedException {
    long newLeaseTime = -1;
    if (leaseTime != -1) {
        newLeaseTime = waitTime*2;
    }
    
    long time = System.currentTimeMillis();
    long remainTime = -1;
    if (waitTime != -1) {
        remainTime = unit.toMillis(waitTime);
    }
    //允许加锁失败节点个数限制为0 相当于是必须所有的服务器加锁成功
    int failedLocksLimit = failedLocksLimit();
    List<RLock> lockedLocks = new ArrayList<RLock>(locks.size());
    //遍历所有节点通过EVAL命令执行lua加锁
    for (ListIterator<RLock> iterator = locks.listIterator(); iterator.hasNext();) {
        RLock lock = iterator.next();
        boolean lockAcquired;
        try {
        	//去获取锁
            if (waitTime == -1 && leaseTime == -1) {
                lockAcquired = lock.tryLock();
            } else {
                long awaitTime = unit.convert(remainTime, TimeUnit.MILLISECONDS);
                lockAcquired = lock.tryLock(awaitTime, newLeaseTime, unit);
            }
        } catch (Exception e) {
            lockAcquired = false;
        }
        
        if (lockAcquired) {
            lockedLocks.add(lock);
        } else {
        	//如果是没有锁成功直接结束
            if (locks.size() - lockedLocks.size() == failedLocksLimit()) {
                break;
            }
			//以后流程就是判断锁了,基本上到了这里就是释放锁了,因为不允许加锁失败
            if (failedLocksLimit == 0) {
                unlockInner(lockedLocks);
                if (waitTime == -1 && leaseTime == -1) {
                    return false;
                }
                failedLocksLimit = failedLocksLimit();
                lockedLocks.clear();
                // reset iterator
                //重新去执行一遍加锁
                while (iterator.hasPrevious()) {
                    iterator.previous();
                }
            } else {
                failedLocksLimit--;
            }
        }
        //计算 目前从各个节点获取锁已经消耗的总时间,如果已经等于最大等待时间,则认定最终申请锁失败,返回false
        if (remainTime != -1) {
            remainTime -= (System.currentTimeMillis() - time);
            time = System.currentTimeMillis();
            if (remainTime <= 0) {
                unlockInner(lockedLocks);
                return false;
            }
        }
    }

    if (leaseTime != -1) {
        List<RFuture<Boolean>> futures = new ArrayList<RFuture<Boolean>>(lockedLocks.size());
        for (RLock rLock : lockedLocks) {
            RFuture<Boolean> future = rLock.expireAsync(unit.toMillis(leaseTime), TimeUnit.MILLISECONDS);
            futures.add(future);
        }
        
        for (RFuture<Boolean> rFuture : futures) {
            rFuture.syncUninterruptibly();
        }
    }
    return true;
}

protected int failedLocksLimit() {
    return 0;
}

7、红锁

  1、源码

   Config config1 = new Config();
config1.useSingleServer().setAddress(redis://172.0.0.1:5378).setPassword(a123456).setDatabase(0);
         RedissonClient redissonClient1 = Redisson.create(config1);
   Config config2 = new Config();
config2.useSingleServer().setAddress(redis://172.0.0.1:5379).setPassword(a123456).setDatabase(0);
         RedissonClient redissonClient2 = Redisson.create(config2);
   Config config3 = new Config();
config3.useSingleServer().setAddress(redis://172.0.0.1:5380).setPassword(a123456).setDatabase(0);
         RedissonClient redissonClient3 = Redisson.create(config3);

//获取多个 RLock 对象
   RLock lock1 = redissonClient1.getLock(lockKey);
   RLock lock2 = redissonClient2.getLock(lockKey);
   RLock lock3 = redissonClient3.getLock(lockKey);


   /根据多个 RLock 对象构建 RedissonRedLock (最核心的差别就在这里)/
   RedissonRedLock redLock = new RedissonRedLock(lock1, lock2, lock3);
  try {
      /**
       * 4.尝试获取锁
       * waitTimeout 尝试获取锁的最大等待时间,超过这个值,则认为获取锁失败
       * leaseTime   锁的持有时间,超过这个时间锁会自动失效(值应设置为大于业务处理的时间,确保在锁有效期内业务能处理完)
       */
      boolean res = redLock.tryLock((long)waitTimeout, (long)leaseTime, TimeUnit.SECONDS);

      if (res) {
         //成功获得锁,在这里处理业务
      }
   } catch (Exception e) {
      throw new RuntimeException("lock fail");
   }finally{
      //无论如何, 最后都要解锁
      redLock.unlock();
   }
public class RedissonRedLock extends RedissonMultiLock {

    /**
     * Creates instance with multiple {@link RLock} objects.
     * Each RLock object could be created by own Redisson instance.
     * 
     * @param locks - array of locks
     */
    public RedissonRedLock(RLock... locks) {
        super(locks);
    }

    @Override
    //锁可以失败的次数,锁的数量-锁成功客户端最小的数量
    protected int failedLocksLimit() {
        return locks.size() - minLocksAmount(locks);
    }
    
    //锁的数量 / 2 + 1,例如有3个客户端加锁,那么最少需要2个客户端加锁成功
    protected int minLocksAmount(final List<RLock> locks) {
        return locks.size()/2 + 1;
    }

    @Override
    public void unlock() {
        unlockInner(locks);
    }

}
public boolean tryLock(long waitTime, long leaseTime, TimeUnit unit) throws InterruptedException {
	//新的失效时间
	long newLeaseTime = -1;
    if (leaseTime != -1) {
    	//如果等待时间设置了,那么将等待时间 * 2
        newLeaseTime = waitTime*2;
    }
    
    long time = System.currentTimeMillis();
    //剩余时间
    long remainTime = -1;
    if (waitTime != -1) {
        remainTime = unit.toMillis(waitTime);
    }
    //允许加锁失败节点个数限制(N-(N/2+1))
    int failedLocksLimit = failedLocksLimit();
    List<RLock> lockedLocks = new ArrayList<RLock>(locks.size());
    //遍历所有节点通过EVAL命令执行lua加锁
    for (ListIterator<RLock> iterator = locks.listIterator(); iterator.hasNext();) {
        RLock lock = iterator.next();
        boolean lockAcquired;
        try {
        	//调用tryLock方法去获取锁,如果获取锁成功,则lockAcquired=true
            if (waitTime == -1 && leaseTime == -1) {
                lockAcquired = lock.tryLock();
            } else {
                long awaitTime = unit.convert(remainTime, TimeUnit.MILLISECONDS);
                lockAcquired = lock.tryLock(awaitTime, newLeaseTime, unit);
            }
        } catch (Exception e) {
        	//抛出异常表示获取锁失败
            lockAcquired = false;
        }
        
        if (lockAcquired) {
        	//如果获取到锁则添加到已获取锁集合中
            lockedLocks.add(lock);
        } else {
        	//计算已经申请锁失败的节点是否已经到达 允许加锁失败节点个数限制 (N-(N/2+1))
	     	//如果已经到达, 就认定最终申请锁失败,则没有必要继续从后面的节点申请了
	     	//因为 Redlock 算法要求至少N/2+1 个节点都加锁成功,才算最终的锁申请成功
            if (locks.size() - lockedLocks.size() == failedLocksLimit()) {
                break;
            }

			//如果最大失败次数等于0
            if (failedLocksLimit == 0) {
            	//释放所有的锁,RedLock加锁失败
                unlockInner(lockedLocks);
                if (waitTime == -1 && leaseTime == -1) {
                    return false;
                }
                failedLocksLimit = failedLocksLimit();
                lockedLocks.clear();
                // reset iterator
                //重置迭代器 重试再次获取锁
                while (iterator.hasPrevious()) {
                    iterator.previous();
                }
            } else {
            	// 失败的限制次数减一
                // 比如3个redis实例,最大的限制次数是1,如果遍历第一个redis实例,失败了,那么failedLocksLimit会减成0
                // 如果failedLocksLimit就会走上面的if逻辑,释放所有的锁,然后返回false
                failedLocksLimit--;
            }
        }
        //计算 目前从各个节点获取锁已经消耗的总时间,如果已经等于最大等待时间,则认定最终申请锁失败,返回false
        if (remainTime != -1) {
            remainTime -= (System.currentTimeMillis() - time);
            time = System.currentTimeMillis();
            if (remainTime <= 0) {
                unlockInner(lockedLocks);
                return false;
            }
        }
    }

    if (leaseTime != -1) {
        List<RFuture<Boolean>> futures = new ArrayList<RFuture<Boolean>>(lockedLocks.size());
        for (RLock rLock : lockedLocks) {
            RFuture<Boolean> future = rLock.expireAsync(unit.toMillis(leaseTime), TimeUnit.MILLISECONDS);
            futures.add(future);
        }
        
        for (RFuture<Boolean> rFuture : futures) {
            rFuture.syncUninterruptibly();
        }
    }
    //如果逻辑正常执行完则认为最终申请锁成功,返回true
    return true;
}

​   其实红锁的思路和基本锁的流程是一样的,唯一的不同就是上面分别进行去不同的服务器先加锁,因为 Redlock 算法要求至少N/2+1 个节点都加锁成功,才算最终的锁申请成功


  2、为啥需要红锁

     1、锁丢失

​   ​    1、 Redis的master节点上拿到了锁;

​   ​  ​  2、但是这个加锁的key还没有同步到slave节点;

​   ​  ​  3、master故障,发生故障转移,slave节点升级为master节点;

​   ​     4、​ 导致锁丢失。


​   ​   2、持有同一把锁(竞态模型场景)

​ ​ ​ ​ ​ ​  为了避免Redis宕机引起锁服务不可用, 需要为Redis实例(master)增加热备(slave),如果master不可用则将slave提升为master。这种主从的配置方式存在一定的安全风险,由于Redis的主从复制是异步进行的, 可能会发生多个客户端同时持有一个锁的现象。


​   ​   3、竞态模型

​   ​   1、Client A 获得在master节点获得了锁

   ​   2、在master将key备份到slave节点之前,master宕机

​ ​   ​   3、slave 被提升为master

​ ​   ​   4、Client B 在新的master节点处获得了锁,Client A也持有这个锁。


8、读写锁

​ ​   ​  具体参考这篇博客:https://www.cnblogs.com/wang-meng/p/12543108.html


9、重入锁

​  1、可重入加锁机制

public void lock() {
    RLock lock = redissonSingle.getLock("myLock");
    try {
        lock.lock();

        // 执行业务
        doBusiness();

        lock.lock();

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        // 释放锁
        lock.unlock();
        lock.unlock();
        logger.info("任务执行完毕, 释放锁!");
    }
}

我们再分析一下加锁那段 lua 代码:

if (redis.call('exists', KEYS[1]) == 0) then " +
   "redis.call('hincrby', KEYS[1], ARGV[2], 1); " +
   "redis.call('pexpire', KEYS[1], ARGV[1]); " +
   "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]); " +
    "return nil; " +
    "end; " +
"return redis.call('pttl', KEYS[1]);"

​  第一个 if 判断肯定不成立,exists myLock 会显示锁 key 已经存在。第二个 if 判断会成立,因为 myLock 的 hash 数据结构中包含的那个 ID 即客户端 1 的 ID,此时就会执行可重入加锁的逻辑,使用:hincrby myLock 285475da-9152-4c83-822a-67ee2f116a79:52 1 对客户端 1 的加锁次数加 1。此时 myLock 数据结构变为下面这样:

127.0.0.1:6379> HGETALL myLock
1) "285475da-9152-4c83-822a-67ee2f116a79:52"
2) "2"

到这里,就明白了 hash 结构的 key 是锁的名称,field 是客户端 ID,value 是该客户端加锁的次数,加锁支持可重入锁,那么解锁呢?


10、锁的释放

lock.unlock()
    @Override
    public void unlock() {
    	// 1. 异步释放锁
        Boolean opStatus = get(unlockInnerAsync(Thread.currentThread().getId()));
        if (opStatus == null) {
            throw new IllegalMonitorStateException("attempt to unlock lock, not locked by current thread by node id: "
                    + id + " thread-id: " + Thread.currentThread().getId());
        }
        if (opStatus) {
	        // 取消 Watch Dog 机制
            cancelExpirationRenewal();
        }

//        Future<Void> future = unlockAsync();
//        future.awaitUninterruptibly();
//        if (future.isSuccess()) {
//            return;
//        }
//        if (future.cause() instanceof IllegalMonitorStateException) {
//            throw (IllegalMonitorStateException)future.cause();
//        }
//        throw commandExecutor.convertException(future);
    }
protected RFuture<Boolean> unlockInnerAsync(long threadId) {
    return commandExecutor.evalWriteAsync(getName(), LongCodec.INSTANCE, RedisCommands.EVAL_BOOLEAN,
            // 判断锁 key 是否存在
            "if (redis.call('exists', KEYS[1]) == 0) then " +
                "redis.call('publish', KEYS[2], ARGV[1]); " +
                "return 1; " +
            "end;" +
            "if (redis.call('hexists', KEYS[1], ARGV[3]) == 0) then " +
                "return nil;" +
            "end; " +
            // 将该客户端对应的锁的 hash 结构的 value 值递减为 0 后再进行删除
            // 然后再向通道名为 redisson_lock__channel publish 一条 UNLOCK_MESSAGE 信息
            "local counter = redis.call('hincrby', KEYS[1], ARGV[3], -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; "+
            "end; " +
            "return nil;",
            Arrays.<Object>asList(getName(), getChannelName()), LockPubSub.unlockMessage, internalLockLeaseTime, getLockName(threadId));

}
void cancelExpirationRenewal() {
    Timeout task = expirationRenewalMap.remove(getEntryName());
    if (task != null) {
        task.cancel();
    }
}
  1. 删除锁(这里注意可重入锁,在上面的脚本中有详细分析)。
  2. 广播释放锁的消息,通知阻塞等待的进程(向通道名为 redisson_lock__channel publish 一条 UNLOCK_MESSAGE 信息)。
  3. 取消 Watch Dog 机制,即将 RedissonLock.EXPIRATION_RENEWAL_MAP 里面的线程 id 删除,并且 cancel 掉 Netty 的那个定时任务线程

11、流程图

在这里插入图片描述

12、参考

https://blog.csdn.net/u010963948/article/details/79240050.

https://blog.csdn.net/zilong_zilong/article/details/78252037.

https://zhuanlan.zhihu.com/p/135864820.


13、结束

整理不易,记得点个赞,你的支持是我最大的动力

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值