Home > Database > Redis > body text

How long is the redis distributed lock timeout?

anonymity
Release: 2019-06-05 13:31:33
Original
8539 people have browsed it

There are generally three ways to implement distributed locks: 1. Database optimistic lock; 2. Redis-based distributed lock; 3. ZooKeeper-based distributed lock.

Here we introduce the implementation of distributed locks based on Redis.

How long is the redis distributed lock timeout?

Properties of distributed locks:

Reliability. First of all, in order to ensure that the distributed lock is available, we must at least ensure that the lock implementation meets the following four conditions at the same time:

Mutual exclusivity. At any time, only one client can hold the lock.

No deadlock will occur. Even if a client crashes while holding the lock without actively unlocking it, it is guaranteed that other clients can subsequently lock it.

Having fault tolerance. As long as most Redis nodes are running normally, the client can lock and unlock.

The trouble should end it. The locking and unlocking must be done by the same client. The client itself cannot unlock the lock added by others.

Code implementation component dependency

First we need to introduce the Jedis open source component through Maven and add the following code to the pom.xml file:

<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>2.9.0</version>
</dependency>
Copy after login

Correct posture for locking code

Talk is cheap, show me the code. First show the code, and then slowly explain why it is implemented this way:

public class RedisTool {
    private static final String LOCK_SUCCESS = "OK";
    private static final String SET_IF_NOT_EXIST = "NX";
    private static final String SET_WITH_EXPIRE_TIME = "PX";
    /**
     * 尝试获取分布式锁
     * @param jedis Redis客户端
     * @param lockKey 锁
     * @param requestId 请求标识
     * @param expireTime 超期时间
     * @return 是否获取成功
     */
    public static boolean tryGetDistributedLock(Jedis jedis, String lockKey, String requestId, int expireTime) {
        String result = jedis.set(lockKey, requestId, SET_IF_NOT_EXIST, SET_WITH_EXPIRE_TIME, expireTime);
        if (LOCK_SUCCESS.equals(result)) {
            return true;
        }
        return false;
    }
}
Copy after login

As you can see, we only need one line of code to lock: jedis.set(String key, String value, String nxxx, String expx, int time ), this set() method has a total of five formal parameters:

The first one is key. We use key as the lock because key is unique.

The second one is value. What we pass is requestId. Many children may not understand. Isn’t it enough to have a key as a lock? Why do we need to use value? The reason is that when we talked about reliability above, the distributed lock must meet the fourth condition to unlock the bell and the person holding the bell must be the person who tied the bell. By assigning the value to requestId, we will know which request added the lock. When unlocking Then you can have a basis. requestId can be generated using the UUID.randomUUID().toString() method.

The third one is nxxx. We fill in this parameter with NX, which means SET IF NOT EXIST, that is, when the key does not exist, we perform the set operation; if the key already exists, no operation is performed;

The fourth one is expx. This parameter we pass is PX, which means we want to add an expiration setting to this key. The specific time is determined by the fifth parameter.

The fifth parameter is time, which corresponds to the fourth parameter and represents the expiration time of the key.

In general, executing the above set() method will only lead to two results: 1. There is currently no lock (key does not exist), then perform the lock operation and set a validity period for the lock , and value represents the locked client. 2. The lock already exists, no operation is performed.

Our locking code meets the three conditions described in our reliability section. First, set() adds the NX parameter, which ensures that if the key already exists, the function will not be called successfully, that is, only one client can hold the lock, satisfying mutual exclusion. Secondly, since we set an expiration time for the lock, even if the lock holder crashes later and is not unlocked, the lock will be automatically unlocked (that is, the key is deleted) when the expiration time is reached, and no deadlock will occur. Finally, because we assign value to requestId, which represents the locked client request identification, then when the client is unlocking, it can be verified whether it is the same client. Since we only consider the scenario of Redis stand-alone deployment, we will not consider fault tolerance for the time being.

The above is the detailed content of How long is the redis distributed lock timeout?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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