Home Database Redis How to develop distributed lock functions using Redis and Java

How to develop distributed lock functions using Redis and Java

Sep 21, 2023 am 08:40 AM
java redis Distributed lock

How to develop distributed lock functions using Redis and Java

How to use Redis and Java to develop distributed lock function

  1. Introduction
    Distributed lock is to achieve mutual exclusion of access to shared resources in a distributed system a mechanism. When multiple nodes access shared resources at the same time, it is necessary to ensure that only one node is accessing and other nodes need to wait. Redis is a commonly used in-memory database with high performance and high reliability, and is very suitable for implementing distributed locks.
  2. Redis's setnx command
    Redis's setnx command can be used to set the value of a key, but the setting operation will only be performed when the key does not exist. This feature can be used to implement distributed lock acquisition operations. Use the setnx command to first try to set a key with an expiration time. If the setting is successful, it means that the lock has been acquired successfully. Otherwise, it means that the lock has been acquired by other nodes.
  3. Java code example
    The following is a sample code that uses Java language and Redis to implement distributed locks:
import redis.clients.jedis.Jedis;

public class DistributedLock {
    private static final String LOCK_KEY = "distributed_lock";
    private static final int LOCK_TIMEOUT = 3 * 1000; // 锁的超时时间,单位为毫秒
    
    private Jedis jedis;

    public DistributedLock(Jedis jedis) {
        this.jedis = jedis;
    }

    public boolean lock() {
        long start = System.currentTimeMillis();
        try {
            while (true) {
                String result = jedis.set(LOCK_KEY, "locked", "NX", "PX", LOCK_TIMEOUT);
                if ("OK".equals(result)) {
                    return true;
                } else {
                    // 进行重试
                    Thread.sleep(100);
                }
                long end = System.currentTimeMillis();
                if (end - start > LOCK_TIMEOUT) {
                    // 超时退出
                    return false;
                }
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            return false;
        }
    }

    public void unlock() {
        jedis.del(LOCK_KEY);
    }
}
Copy after login
  1. Example description
    In the above example code , using the Jedis library to operate Redis. First, a constant LOCK_KEY is defined as the key of the distributed lock. This key must remain unique among all nodes. In addition, a LOCK_TIMEOUT constant is set to represent the lock timeout.

In the lock method, first get the current time as the start time, and then use an infinite loop to try to acquire the distributed lock. In the loop, use the set command of Redis to perform the setting operation. The set key is LOCK_KEY, the value is "locked", and NX and are set. PX option, NX means that the setting operation is performed only when the key does not exist, PX means that the expiration time of the set key is LOCK_TIMEOUT milliseconds.

If the setting is successful, it means that the lock is acquired successfully, and the method returns true; otherwise, retry will continue, and 100 milliseconds will be waited for each retry. At the same time, it is also necessary to determine whether the time to acquire the lock exceeds the value of LOCK_TIMEOUT. If it exceeds, it means that the waiting time to acquire the lock has been too long, give up acquiring the lock, and return false.

In the unlock method, delete the key of the distributed lock by calling the del command.

  1. Calling example
    The following is a calling example using the sample code:
import redis.clients.jedis.Jedis;

public class LockTest {
    public static void main(String[] args) {
        Jedis jedis = new Jedis("localhost");
        DistributedLock lock = new DistributedLock(jedis);
        try {
            if (lock.lock()) {
                // 获取到分布式锁后执行需要保护的代码
                System.out.println("获取到分布式锁");
                // ... 执行需要保护的代码
            } else {
                System.out.println("获取分布式锁失败");
            }
        } finally {
            lock.unlock();
        }
    }
}
Copy after login

In the calling example, a Jedis connection object is first created, and then A DistributedLock object, and pass in the Jedis connection object as a parameter. In the try-finally block, first try to acquire the distributed lock. If successful, output "obtained distributed lock", execute the code that needs to be protected, and then release the distributed lock in the finally block.

  1. Summary
    By using Redis and Java development, we can easily implement the distributed lock function. The lock acquisition operation can be implemented using the Redis setnx command, and the Java code can easily call the Redis command and encapsulate it into a distributed lock class. In actual applications, the timeout of distributed locks can be adjusted as needed to ensure that the waiting time to acquire the lock will not be too long, thus improving the performance and concurrency of the system.

The above is the detailed content of How to develop distributed lock functions using Redis and Java. 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)

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

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)

PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP vs. Python: Use Cases and Applications PHP vs. Python: Use Cases and Applications Apr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

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

How to configure slow query log in centos redis How to configure slow query log in centos redis Apr 14, 2025 pm 04:54 PM

Enable Redis slow query logs on CentOS system to improve performance diagnostic efficiency. The following steps will guide you through the configuration: Step 1: Locate and edit the Redis configuration file First, find the Redis configuration file, usually located in /etc/redis/redis.conf. Open the configuration file with the following command: sudovi/etc/redis/redis.conf Step 2: Adjust the slow query log parameters in the configuration file, find and modify the following parameters: #slow query threshold (ms)slowlog-log-slower-than10000#Maximum number of entries for slow query log slowlog-max-len

See all articles