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
- Analysis
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:
- Redlock-rb (Ruby implementation). There is also a fork of Redlock-rb that adds a gem for easy distribution.
- RedisQueuedLocks (Ruby implementation).
- Redlock-py (Python implementation).
- Pottery (Python implementation).
- Aioredlock (Asyncio Python implementation).
- RedisMutex (PHP implementation with both Redis extension and Predis library clients support).
- Redlock-php (PHP implementation).
- cheprasov/php-redis-lock (PHP library for locks).
- rtckit/react-redlock (Async PHP implementation).
- Redsync (Go implementation).
- Redisson (Java implementation).
- Redis::DistLock (Perl implementation).
- Redlock-cpp (C++ implementation).
- Redis-plus-plus (C++ implementation).
- Redlock-cs (C#/.NET implementation).
- RedLock.net (C#/.NET implementation). Includes async and lock extension support.
- ScarletLock (C# .NET implementation with configurable datastore).
- Redlock4Net (C# .NET implementation).
- node-redlock (NodeJS implementation). Includes support for lock extension.
- simple-redis-mutex (Node.js implementation) Available as an NPM package.
- Deno DLM (Deno implementation)
- Rslock (Rust implementation). Includes async and lock extension support.
Feedback
Was this page helpful?
Provide feedbackThank you very much for your feedback. We will continue working to improve the documentation.See the reply and handling status in My Cloud VOC.
For any further questions, feel free to contact us through the chatbot.
Chatbot