Mastering Redis Distributed Locks with Jedis: A Hands‑On Guide
This article explains how to implement a Redis distributed lock in Java using Jedis, covering Maven setup, lock creation with setNX, safe lock release via Lua scripts, and a realistic 100,000‑user flash‑sale simulation to demonstrate concurrency control.
This article demonstrates how to implement a Redis distributed lock in Java using the Jedis client, illustrated with a simulated flash‑sale (order‑grabbing) scenario.
Creating a lock with Jedis setNX
First add the Jedis dependency to your Maven pom:
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>The lock is created with set(key, val, "NX", "PX", timeout), where NX ensures the key is set only if it does not already exist, and PX sets the expiration time in milliseconds.
Example method:
public boolean setnx(String key, String val) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
if (jedis == null) {
return false;
}
return jedis.set(key, val, "NX", "PX", 1000 * 60).equalsIgnoreCase("OK");
} catch (Exception ex) {
} finally {
if (jedis != null) {
jedis.close();
}
}
return false;
}A Spring MVC endpoint can invoke this method:
@GetMapping("/setnx/{key}/{val}")
public boolean setnx(@PathVariable String key, @PathVariable String val) {
return jedisCom.setnx(key, val);
}When the lock is acquired, the key has a limited TTL, preventing other users from obtaining the lock until it expires or is released.
Releasing the lock
To delete the lock safely, the value stored with the lock must be provided. The implementation builds a Lua script that deletes the key only if its value matches:
public int delnx(String key, String val) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
if (jedis == null) {
return 0;
}
StringBuilder sb = new StringBuilder();
sb.append("if redis.call('get','").append(key).append("')=='")
.append(val).append("' then return redis.call('del','").append(key).append("') else return 0 end");
return Integer.valueOf(jedis.eval(sb.toString()).toString());
} catch (Exception ex) {
} finally {
if (jedis != null) {
jedis.close();
}
}
return 0;
}Corresponding endpoint:
@GetMapping("/delnx/{key}/{val}")
public int delnx(@PathVariable String key, @PathVariable String val) {
return jedisCom.delnx(key, val);
}Simulating 100 000 concurrent users
The article then creates 100 000 virtual users, initializes a stock of 10 items, and uses parallelStream() to let each user attempt to acquire the lock, place an order, and release the lock.
private String qiang(String b) {
long startTime = System.currentTimeMillis();
while ((startTime + timeout) >= System.currentTimeMillis()) {
if (nKuCuen <= 0) {
break;
}
if (jedisCom.setnx(shangpingKey, b)) {
try {
if (nKuCuen <= 0) {
break;
}
TimeUnit.SECONDS.sleep(1);
nKuCuen -= 1;
return b + "抢单成功,所剩库存:" + nKuCuen;
} finally {
jedisCom.delnx(shangpingKey, b);
}
}
}
return "";
}Key points of the simulation:
parallelStream() mimics many users competing for the same item.
The loop continues for up to timeout milliseconds while the lock is not obtained.
Both before and after acquiring the lock the remaining stock is checked.
After a successful purchase the lock is released with delnx.
Running the test shows that only the first request succeeds, the key has a valid TTL, and subsequent requests fail until the lock expires, as illustrated by the following screenshots:
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.
