Redis Distributed Lock Implementation Using Jedis with a High-Concurrency Order Simulation
This article explains how to implement a Redis-based distributed lock using Jedis in Java, covering lock creation with SETNX, lock expiration, safe lock release via Lua scripts, and demonstrates the approach by simulating a 100,000-user concurrent order‑grabbing scenario.
The article introduces Redis distributed locks, a common interview topic, and shows how to apply them in a simulated order‑grabbing scenario. It assumes a Docker‑based Redis test environment and focuses on Java code using the Jedis client.
Creating a Lock with Jedis SETNX
To create a lock, the setnx method uses SET key value NX PX timeout. If the key does not exist, the operation succeeds and returns OK; otherwise it fails, ensuring only one client holds the lock at a time.
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;
}The method is exposed via a Spring @GetMapping endpoint:
@GetMapping("/setnx/{key}/{val}")
public boolean setnx(@PathVariable String key, @PathVariable String val) {
return jedisCom.setnx(key, val);
}Releasing the Lock
Lock release is performed atomically with a Lua script that deletes the key only if its value matches the owner’s value.
public int delnx(String key, String val) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
if (jedis == null) {
return 0;
}
StringBuilder sbScript = new StringBuilder();
sbScript.append("if redis.call('get','").append(key).append("')"
.append("=='").append(val).append("' then ")
.append(" return redis.call('del','").append(key).append("')")
.append(" else return 0 end");
return Integer.valueOf(jedis.eval(sbScript.toString()).toString());
} catch (Exception ex) {
} finally {
if (jedis != null) {
jedis.close();
}
}
return 0;
} @GetMapping("/delnx/{key}/{val}")
public int delnx(@PathVariable String key, @PathVariable String val) {
return jedisCom.delnx(key, val);
}Simulating 100,000 Concurrent Order Requests
The demo creates 100,000 virtual users, sets an initial stock of 10 items, and uses Java parallel streams to let each user repeatedly try to acquire the lock within a 30‑second timeout. When a lock is obtained, the user sleeps for one second to simulate order processing, decrements the stock, logs success, and finally releases 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 "";
}The main endpoint /qiangdan builds the user list, initializes the stock, and runs the parallel simulation, collecting the usernames of successful purchasers.
Result
Log output shows which users acquired the lock and the remaining stock after each successful purchase. The final response lists all users who successfully placed an order.
Overall, the article demonstrates a practical Redis distributed‑lock pattern, safe lock release with Lua, and a stress‑test using Java’s parallel streams.
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 Captain
Focused on Java technologies: SSM, the Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading; occasionally covers DevOps tools like Jenkins, Nexus, Docker, ELK; shares practical tech insights and is dedicated to full‑stack Java development.
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.
