Help Center/ GeminiDB/ GeminiDB Redis API/ Development Reference/ Implementing Distributed Locks Using Lua Scripts for GeminiDB Redis API
Updated on 2025-01-03 GMT+08:00

Implementing Distributed Locks Using Lua Scripts for GeminiDB Redis API

In a distributed system, distributed locks are used to ensure that only one process or thread can execute a specific code snippet at a time.

This section describes how to use Lua scripts to implement distributed locks.

Redis Distributed Locks

Redis offers a basic locking mechanism that relying on atomic commands to implement distributed locks. One of the simplest ways to implement distributed locks is using the SETNX command. SETNX sets the value of a key only if the key does not exist. In this way, the key value is successfully set for the first process that obtains a lock, and subsequent processes that attempt to obtain the lock fail until the lock is released.

To prevent a lock from being released forever (for example, the process that holds the lock crashes), an expiration time is usually set for the lock using the EXPIRE command. In versions later than Redis 2.6.12, the EX and NX options are added to the SET command. You can set the expiration time when setting the key. This operation is atomic.

  • Acquiring a lock

You can run the following command to acquire a lock:

SET resource_name my_random_value NX PX 30000

The NX parameter is used to check whether the key exists. If it does not, that is, no one holds the lock, the lock is successfully acquired.

The PX parameter is mandatory and is used to set a lock validity period accurate to milliseconds. If a lock holder exits abnormally or a lock expires, the lock is automatically released to prevent deadlocks.

  • Releasing a lock

Releasing a lock is more complex. A lock can be released only by its holder. To release multiple locks in sequence, you need to execute a Lua script.

Lua script:

if redis.call("get",KEYS[1]) == ARGV[1] then
    return redis.call("del",KEYS[1])
else
    return 0
end

The Lua script must be executed together with the EVAL command, for example:

EVAL 'if redis.call("get",KEYS[1]) == ARGV[1] then return redis.call("del",KEYS[1]) else return 0 end' 1 resource_name my_random_value
This script ensures that only the holder can release the lock.
  • Analysis
    The preceding solution is easy to use but has the following disadvantages:
    • The expired lock is released, but transactions are incomplete.
    • Reentrant locks are not supported.
    • No notification mechanism is available. Locks need to be preempted in polling mode, consuming a lot of CPU resources.

For production applications, the Redis distributed lock library is recommended to balance functions and performance.

The following uses Redisson as an example to describe how to use the Redis distributed lock library.

Implementing Distributed Locks Using Redisson

Redisson is a Redis Java client and provides the distributed locking feature. A distributed lock is a mechanism used to synchronously access shared resources in a distributed system. Redisson implements distributed locks through atomic operations of Redis to ensure that only one client can access a resource at a time.

Distributed locks based on Redisson have the following features:

  • High efficiency: Redis features high performance and memory storage, making distributed lock operations very fast.
  • Easy to use: Various APIs allow developers to easily use distributed locks in Java applications.
  • Reliability: Distributed locks based on Redisson are highly reliable. Even if a partition or node breaks down, the locks are not affected.

Example

import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;

public class LockExamples {
    public static void main(String[] args) {
        // Creates a Redisson client.
        Config config = new Config();
        config.useSingleServer().setAddress("redis://127.0.0.1:7200");
        RedissonClient redisson = Redisson.create(config);

        // Obtains a distributed lock.
        RLock lock = redisson.getLock("myLock");

        try {
        // Acquires a lock.
            lock.lock();
            System.out.println("Lock acquired, executing critical section...");

           // Executes the code to acquire a lock.
            // ...
            System.out.println("Critical section executed, releasing lock...");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
          // Release a lock.
            lock.unlock();
        }

      // Closes the Redisson client.
        redisson.shutdown();
    }
}

Other Recommended Implementations of Distributed Locks

Redisson is a Java client which has implemented distributed locks for various programming languages. Here are a few links to available implementations from the Redis official website: