Home > Database > Redis > What is the principle of using Redisson red lock in Redis

What is the principle of using Redisson red lock in Redis

王林
Release: 2023-05-30 21:35:18
forward
1466 people have browsed it

Why use Redis's red lock

The problem of master-slave structure distributed lock

The simplest way to implement Redis distributed lock is to create it in Redis A key, this key has an expiration time (TTL) to ensure that the lock will eventually be released automatically. When the client releases the resource (unlocks it), the key will be deleted.

On the surface it seems to work well, but there is a serious single point of failure problem: what if Redis hangs? You might say that this problem can be solved by adding a slave node. But this usually doesn't work. Redis's master-slave synchronization is usually asynchronous, so this cannot achieve exclusive use of resources.

There is an obvious race condition in this scenario (master-slave structure):

  • Client A acquires the lock from the master

  • Before the master synchronizes the lock to the slave, the master crashes.

  • The slave node is promoted to the master node

  • Client B obtains the lock from the new master

    • The resource corresponding to this lock has been acquired by client A before. Security failure!

#The program is sometimes such a coincidence. For example, when a node hangs up, multiple clients happen to obtain the lock at the same time. As long as you can tolerate this low probability of error, there's no problem adopting this replication-based solution. Otherwise, we recommend that you implement the solution described below.

Solution: Use red lock

Introduction

Redis introduces the concept of red lock for this situation. In a red lock system, the successful sign of acquiring or releasing a lock is that the operation is successful on more than half of the nodes.

Principle

Assuming there are N Redis masters in the distributed environment of Redis.. These nodes are completely independent of each other, and there is no master-slave replication or other cluster coordination mechanism. We have previously explained how to safely acquire and release locks in a single instance of Redis. We ensure that the lock will be acquired and released using this method on every (N) instance. In this example, we assume that there are 5 Redis master nodes. This is a reasonable setting, so we need to run these instances on 5 machines or 5 virtual machines to ensure that they will not all go down at the same time. .

In order to obtain the lock, the client should perform the following operations:

  • Get the current Unix time in milliseconds.

  • Try to acquire locks from N instances in sequence, using the same key and random values.

    • When setting a lock to Redis, the client should set a network connection and response timeout, which should be less than the lock expiration time.

    • If your lock automatically expires in 10 seconds, the timeout should be set between 5-50 milliseconds. Prevent the client from waiting endlessly for response results even when the Redis server is down. When no response from the server is received within the specified time, the client should try to connect to other Redis instances as soon as possible.

  • #The client uses the current time minus the time when it started to acquire the lock (the time recorded in step 1) to get the time used to acquire the lock.

    • #The condition for successfully acquiring the lock is that the lock must be acquired from the majority of Redis nodes (3 nodes), and the use time cannot exceed the lock expiration time.

  • If the lock is acquired, the real valid time of the key is equal to the valid time minus the time used to acquire the lock (the result calculated in step 3).

  • If for some reason, the lock acquisition fails (the lock is not acquired on at least N/2 1 Redis instances or the lock acquisition time has exceeded the effective time), the client should Unlock all Redis instances (even if some Redis instances are not locked successfully at all).

Redisson red lock instance

Official website

Official github: 8. Distributed lock and synchronizer· redisson/redisson Wik

The Redisson red lock based on Redis The RedissonRedLock object implements the locking algorithm introduced by Redlock. This object can also be used to associate multiple RLock objects as a red lock. Each RLock object instance can come from a different Redisson instance.

RLock lock1 = redissonInstance1.getLock("lock1");
RLock lock2 = redissonInstance2.getLock("lock2");
RLock lock3 = redissonInstance3.getLock("lock3");
 
RedissonRedLock lock = new RedissonRedLock(lock1, lock2, lock3);
// 同时加锁:lock1 lock2 lock3
// 红锁在大部分节点上加锁成功就算成功。
lock.lock();
...
lock.unlock();
Copy after login

Everyone knows that if some Redis nodes responsible for storing certain distributed locks go down and these locks happen to be in a locked state, these locks will become locked. In order to avoid this situation from happening, Redisson internally provides a watchdog that monitors the lock. Its function is to continuously extend the validity period of the lock before the Redisson instance is closed. By default, the watchdog check lock timeout is 30 seconds, which can also be specified separately by modifying Config.lockWatchdogTimeout.

Redisson can also specify the locking time by locking and setting the leaseTime parameter. After this time has elapsed, the lock will automatically unlock.

RedissonRedLock lock = new RedissonRedLock(lock1, lock2, lock3);
// 给lock1,lock2,lock3加锁,如果没有手动解开的话,10秒钟后将会自动解开
lock.lock(10, TimeUnit.SECONDS);
 
// 为加锁等待100秒时间,并在加锁成功10秒钟后自动解开
boolean res = lock.tryLock(100, 10, TimeUnit.SECONDS);
...
lock.unlock();
Copy after login

Redisson Red Lock Principle

RedissonRedLock extends RedissonMultiLock, so in fact, redLock.tryLock actually calls: org.redisson.RedissonMultiLock.java#tryLock(), and then calls its similar tryLock (long waitTime, long leaseTime, TimeUnit unit), the input parameters are: tryLock(-1, -1, null)

org.redisson.RedissonMultiLock.java#tryLock(long waitTime, long leaseTime, TimeUnit unit)源码如下:

final List<RLock> locks = new ArrayList<>();
 
/**
 * Creates instance with multiple {@link RLock} objects.
 * Each RLock object could be created by own Redisson instance.
 *
 * @param locks - array of locks
 */
public RedissonMultiLock(RLock... locks) {
    if (locks.length == 0) {
        throw new IllegalArgumentException("Lock objects are not defined");
    }
    this.locks.addAll(Arrays.asList(locks));
}
 
public boolean tryLock(long waitTime, long leaseTime, TimeUnit unit) throws InterruptedException {
    long newLeaseTime = -1;
    if (leaseTime != -1) {
        newLeaseTime = unit.toMillis(waitTime)*2;
    }
    
    long time = System.currentTimeMillis();
    long remainTime = -1;
    if (waitTime != -1) {
        remainTime = unit.toMillis(waitTime);
    }
    long lockWaitTime = calcLockWaitTime(remainTime);
    /**
     * 1. 允许加锁失败节点个数限制(N-(N/2+1))
     */
    int failedLocksLimit = failedLocksLimit();
    /**
     * 2. 遍历所有节点通过EVAL命令执行lua加锁
     */
    List<RLock> acquiredLocks = new ArrayList<>(locks.size());
    for (ListIterator<RLock> iterator = locks.listIterator(); iterator.hasNext();) {
        RLock lock = iterator.next();
        boolean lockAcquired;
        /**
         *  3.对节点尝试加锁
         */
        try {
            if (waitTime == -1 && leaseTime == -1) {
                lockAcquired = lock.tryLock();
            } else {
                long awaitTime = Math.min(lockWaitTime, remainTime);
                lockAcquired = lock.tryLock(awaitTime, newLeaseTime, TimeUnit.MILLISECONDS);
            }
        } catch (RedisResponseTimeoutException e) {
            // 如果抛出这类异常,为了防止加锁成功,但是响应失败,需要解锁所有节点
            unlockInner(Arrays.asList(lock));
            lockAcquired = false;
        } catch (Exception e) {
            // 抛出异常表示获取锁失败
            lockAcquired = false;
        }
        
        if (lockAcquired) {
            /**
             *4. 如果获取到锁则添加到已获取锁集合中
             */
            acquiredLocks.add(lock);
        } else {
            /**
             * 5. 计算已经申请锁失败的节点是否已经到达 允许加锁失败节点个数限制 (N-(N/2+1))
             * 如果已经到达, 就认定最终申请锁失败,则没有必要继续从后面的节点申请了
             * 因为 Redlock 算法要求至少N/2+1 个节点都加锁成功,才算最终的锁申请成功
             */
            if (locks.size() - acquiredLocks.size() == failedLocksLimit()) {
                break;
            }
 
            if (failedLocksLimit == 0) {
                unlockInner(acquiredLocks);
                if (waitTime == -1 && leaseTime == -1) {
                    return false;
                }
                failedLocksLimit = failedLocksLimit();
                acquiredLocks.clear();
                // reset iterator
                while (iterator.hasPrevious()) {
                    iterator.previous();
                }
            } else {
                failedLocksLimit--;
            }
        }
 
        /**
         * 6.计算 目前从各个节点获取锁已经消耗的总时间,如果已经等于最大等待时间,则认定最终申请锁失败,返回false
         */
        if (remainTime != -1) {
            remainTime -= System.currentTimeMillis() - time;
            time = System.currentTimeMillis();
            if (remainTime <= 0) {
                unlockInner(acquiredLocks);
                return false;
            }
        }
    }
 
    if (leaseTime != -1) {
        List<RFuture<Boolean>> futures = new ArrayList<>(acquiredLocks.size());
        for (RLock rLock : acquiredLocks) {
            RFuture<Boolean> future = ((RedissonLock) rLock).expireAsync(unit.toMillis(leaseTime), TimeUnit.MILLISECONDS);
            futures.add(future);
        }
        
        for (RFuture<Boolean> rFuture : futures) {
            rFuture.syncUninterruptibly();
        }
    }
 
    /**
     * 7.如果逻辑正常执行完则认为最终申请锁成功,返回true
     */
    return true;
}
Copy after login

The above is the detailed content of What is the principle of using Redisson red lock in Redis. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template