Home Database Redis Redis distributed lock implementation method

Redis distributed lock implementation method

May 10, 2023 pm 09:01 PM
redis Distributed lock Implementation

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;
Copy after login

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);
Copy after login

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);
Copy after login

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);
}
Copy after login

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();
Copy after login

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);
}
Copy after login

(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);

// 不释放锁
Copy after login

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();
    }

}
Copy after login

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to build the redis cluster mode How to build the redis cluster mode Apr 10, 2025 pm 10:15 PM

Redis cluster mode deploys Redis instances to multiple servers through sharding, improving scalability and availability. The construction steps are as follows: Create odd Redis instances with different ports; Create 3 sentinel instances, monitor Redis instances and failover; configure sentinel configuration files, add monitoring Redis instance information and failover settings; configure Redis instance configuration files, enable cluster mode and specify the cluster information file path; create nodes.conf file, containing information of each Redis instance; start the cluster, execute the create command to create a cluster and specify the number of replicas; log in to the cluster to execute the CLUSTER INFO command to verify the cluster status; make

How to clear redis data How to clear redis data Apr 10, 2025 pm 10:06 PM

How to clear Redis data: Use the FLUSHALL command to clear all key values. Use the FLUSHDB command to clear the key value of the currently selected database. Use SELECT to switch databases, and then use FLUSHDB to clear multiple databases. Use the DEL command to delete a specific key. Use the redis-cli tool to clear the data.

How to read redis queue How to read redis queue Apr 10, 2025 pm 10:12 PM

To read a queue from Redis, you need to get the queue name, read the elements using the LPOP command, and process the empty queue. The specific steps are as follows: Get the queue name: name it with the prefix of "queue:" such as "queue:my-queue". Use the LPOP command: Eject the element from the head of the queue and return its value, such as LPOP queue:my-queue. Processing empty queues: If the queue is empty, LPOP returns nil, and you can check whether the queue exists before reading the element.

How to configure Lua script execution time in centos redis How to configure Lua script execution time in centos redis Apr 14, 2025 pm 02:12 PM

On CentOS systems, you can limit the execution time of Lua scripts by modifying Redis configuration files or using Redis commands to prevent malicious scripts from consuming too much resources. Method 1: Modify the Redis configuration file and locate the Redis configuration file: The Redis configuration file is usually located in /etc/redis/redis.conf. Edit configuration file: Open the configuration file using a text editor (such as vi or nano): sudovi/etc/redis/redis.conf Set the Lua script execution time limit: Add or modify the following lines in the configuration file to set the maximum execution time of the Lua script (unit: milliseconds)

How to set the redis expiration policy How to set the redis expiration policy Apr 10, 2025 pm 10:03 PM

There are two types of Redis data expiration strategies: periodic deletion: periodic scan to delete the expired key, which can be set through expired-time-cap-remove-count and expired-time-cap-remove-delay parameters. Lazy Deletion: Check for deletion expired keys only when keys are read or written. They can be set through lazyfree-lazy-eviction, lazyfree-lazy-expire, lazyfree-lazy-user-del parameters.

How to use the redis command line How to use the redis command line Apr 10, 2025 pm 10:18 PM

Use the Redis command line tool (redis-cli) to manage and operate Redis through the following steps: Connect to the server, specify the address and port. Send commands to the server using the command name and parameters. Use the HELP command to view help information for a specific command. Use the QUIT command to exit the command line tool.

How to implement redis counter How to implement redis counter Apr 10, 2025 pm 10:21 PM

Redis counter is a mechanism that uses Redis key-value pair storage to implement counting operations, including the following steps: creating counter keys, increasing counts, decreasing counts, resetting counts, and obtaining counts. The advantages of Redis counters include fast speed, high concurrency, durability and simplicity and ease of use. It can be used in scenarios such as user access counting, real-time metric tracking, game scores and rankings, and order processing counting.

How to optimize the performance of debian readdir How to optimize the performance of debian readdir Apr 13, 2025 am 08:48 AM

In Debian systems, readdir system calls are used to read directory contents. If its performance is not good, try the following optimization strategy: Simplify the number of directory files: Split large directories into multiple small directories as much as possible, reducing the number of items processed per readdir call. Enable directory content caching: build a cache mechanism, update the cache regularly or when directory content changes, and reduce frequent calls to readdir. Memory caches (such as Memcached or Redis) or local caches (such as files or databases) can be considered. Adopt efficient data structure: If you implement directory traversal by yourself, select more efficient data structures (such as hash tables instead of linear search) to store and access directory information

See all articles