How to Implement a Simple Redis-Based Resource Lock with SET
This guide explains how to use Redis's SET command with NX and EX options to create a simple resource lock, including token generation, lock acquisition, automatic expiration, and safe unlocking with DEL after token verification, while warning against using this method for production distributed locks.
When reading the Redis documentation, an official example shows using Redis to implement a resource lock, which is simple and practical.
1. Lock
Use the SET command:
SET resource_name random_token NX EX max_secondsThe resource name is used as the key, the random token acts as a password for unlocking. NX sets the key only if it does not exist, and EX sets the expiration time in seconds. If the command succeeds, it returns “OK”, indicating the lock has been acquired.
2. Unlock
After acquiring the lock, it will be automatically released after the expiration time if not released manually. The client can also release the lock early using the DEL command, but must first verify the token to ensure only the lock owner can delete the key.
Note: This method should not be used for a production‑grade Redis distributed lock.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java High-Performance Architecture
Sharing Java development articles and resources, including SSM architecture and the Spring ecosystem (Spring Boot, Spring Cloud, MyBatis, Dubbo, Docker), Zookeeper, Redis, architecture design, microservices, message queues, Git, etc.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
