Redis is an open source in-memory data caching system that can store and read data. In a distributed environment, when multiple applications operate on the same resource at the same time, problems with dirty data and data inconsistency may occur. In order to solve this problem, we can introduce distributed locks to ensure data consistency.
This article helps readers understand how to use Redis to implement distributed locks by introducing the application scenarios, principles and implementation methods of Redis distributed locks.
1. Application scenarios
In a distributed system, an application may need to operate multiple resources at the same time. So how to ensure that this application's operations on resources are thread-safe? At this time, distributed locks need to be introduced.
Distributed locks can be used to solve the following problems:
(1) Avoid multiple clients from modifying the same resource at the same time, resulting in data inconsistency.
(2) Prevent the client from making multiple modifications to the same resource due to network delays and other issues.
(3) Prevent the client from occupying resources for too long, causing other clients to be unable to access resources normally.
2. Principle
Redis distributed lock is mainly implemented through the setnx command. The setnx command is an atomic operation in Redis, which ensures that in concurrent operations of multiple clients, only one client can successfully set the key-value pair to Redis.
Next, let’s take a look at the specific implementation of Redis distributed lock.
3. Implementation method
(1) Obtain the lock
In the process of acquiring the lock, we need to use the setnx command to set a key-value pair. If the setting is successful, it means that we have obtained the lock. If the setting is unsuccessful, we need to wait for a period of time and try to obtain the lock again.
First, we obtain the lock through the following code block:
boolean lock = jedis.setnx(key, value) == 1;
Among them, key and value represent the name and value of the lock respectively, and jedis represents the Redis client.
If the name of the lock does not exist in Redis, then the return value of the above code is 1, indicating that the setting is successful and the lock is obtained. If the lock name already exists in Redis, the return value of the above code is 0, indicating that the setting failed and the lock acquisition failed.
(2) Release the lock
In the process of releasing the lock, we need to use the del command to delete the key-value pair in Redis.
First, we release the lock through the following code block:
long result = jedis.del(key);
Among them, key represents the name of the lock, and jedis represents the Redis client.
If the key-value pair in Redis is successfully deleted, the return value of the above code is 1, indicating that the lock is released successfully. If the key-value pair does not exist in Redis, the return value of the above code is 0, indicating that the lock release fails.
(3) Set the expiration time of the lock
In order to prevent the lock from being occupied all the time, we need to set the expiration time of the lock. When the lock holder does not release the lock within a certain period of time, Redis will automatically delete the lock to prevent the lock from being occupied forever.
First, we need to set the expiration time of the lock through the following code block:
jedis.expire(key, timeout);
Among them, key represents the name of the lock, and timeout represents the expiration time of the lock, in seconds.
In order to prevent accidentally deleting other clients' locks, you need to determine whether the value of the lock is consistent with the value you set when you acquired it.
String value = jedis.get(key); if (StringUtils.isNotBlank(value) && value.equals(uuid)) { jedis.del(key); }
Among them, uuid represents the unique identification of the client to obtain the lock.
(4) Prevent locks of other clients from being accidentally deleted
After using the lock, we need to release the lock correctly, otherwise the locks of other clients will be accidentally deleted.
Therefore, in order to prevent the locks of other clients from being accidentally deleted, we need to add a unique identifier to the code.
First, in the process of acquiring the lock, we need to generate a unique identifier for the client, as shown below:
String uuid = UUID.randomUUID().toString();
Then, in the process of acquiring the lock and releasing the lock, we need to Determine whether the value corresponding to the key is equal to the uuid to determine whether the lock is acquired by the current client. In the process of acquiring the lock and releasing the lock, the uuid needs to be set as the value to the value corresponding to the key.
The specific code is as follows:
boolean lock = jedis.setnx(key, uuid) == 1; if (lock) { jedis.expire(key, timeout); } // 释放锁 String value = jedis.get(key); if (StringUtils.isNotBlank(value) && value.equals(uuid)) { jedis.del(key); }
(5) Wrong usage examples
In the process of using distributed locks, if we encounter the following situations, then Will cause deadlock:
// 获取锁 jedis.setnx(key, value); // 不释放锁
Therefore, when using the lock, you must pay attention to releasing the lock correctly, otherwise it will bring unpredictable consequences to the system.
(6) Implementation class
Finally, let’s take a look at how to encapsulate the above code into a Redis distributed lock class.
import redis.clients.jedis.Jedis; import java.util.UUID; public class RedisLock { 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"; private Jedis jedis; public RedisLock(Jedis jedis) { this.jedis = jedis; } /** * 尝试获取分布式锁 * @param key 锁 * @param requestId 请求标识 * @param expireTime 超期时间(秒) * @return 是否获取成功 */ public boolean tryGetDistributedLock(String key, String requestId, int expireTime) { String result = jedis.set(key, requestId, SET_IF_NOT_EXIST, SET_WITH_EXPIRE_TIME, expireTime); return LOCK_SUCCESS.equals(result); } /** * 释放分布式锁 * @param key 锁 * @param requestId 请求标识 * @return 是否释放成功 */ public boolean releaseDistributedLock(String key, String requestId) { String value = jedis.get(key); if (value != null && value.equals(requestId)) { jedis.del(key); return true; } return false; } /** * 获取请求标识 * @return 请求标识 */ public static String getRequestId() { return UUID.randomUUID().toString(); } }
At this point, we have completed the implementation of Redis distributed lock.
4. Summary
This article helps readers understand how to use Redis to implement distributed locks by introducing the application scenarios, principles and implementation methods of Redis distributed locks. Since the implementation of distributed locks is relatively complex, we need to pay attention to some details, such as determining whether the value of the lock is consistent with the value set when acquiring it, and setting uuid as value to key during the process of acquiring and releasing the lock. The corresponding value is medium. Only by using distributed locks correctly can the consistency and reliability of data in a distributed system be ensured.
The above is the detailed content of Redis distributed lock implementation method. For more information, please follow other related articles on the PHP Chinese website!