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.

Java High-Performance Architecture
Java High-Performance Architecture
Java High-Performance Architecture
How to Implement a Simple Redis-Based Resource Lock with SET

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_seconds

The 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.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

redisSET command
Java High-Performance Architecture
Written by

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.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.