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

How to develop distributed lock functions using Redis and Java

WBOY
WBOYOriginal
2023-09-21 08:40:461166browse

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

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:
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