Implementing Distributed Locks with Redis in PHP to Prevent Overselling
This article explains how to prevent overselling in high‑concurrency scenarios by using Redis‑based distributed locks in PHP, detailing initialization, lock acquisition with setnx, unlocking with del, and providing complete sample code along with best‑practice considerations.
In high‑concurrency environments, simultaneous purchase requests can cause overselling; using a Redis‑based distributed lock in PHP ensures that only one process accesses the critical section at a time.
Redis provides the setnx command, which attempts to create a key only if it does not already exist, making it suitable for implementing mutual exclusion across multiple PHP processes.
1. Initialize Redis connection
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);2. Acquire lock
$user_id = 1001; // ID
$goods_id = 2001; // 商品 ID
// Try to acquire the lock; a return value of 1 means success
if ($redis->setnx("lock_{$goods_id}", 1)) {
// Lock acquired, proceed with purchase logic
} else {
// Lock acquisition failed, purchase fails
echo '购买失败';
}3. Release lock
$redis->del("lock_{$goods_id}");4. Full implementation example
$user_id = 1001; // 用户 ID
$goods_id = 2001; // 商品 ID
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
if ($redis->setnx("lock_{$goods_id}", 1)) {
// Simulate inventory check
$stock = 100;
$sold = 50;
if ($sold < $stock) {
echo '购买成功';
} else {
echo '库存不足,购买失败';
}
$redis->del("lock_{$goods_id}"); // Release lock
} else {
echo '购买失败'; // Could not acquire lock
}The article also notes that production‑grade code should handle additional edge cases such as lock timeouts, failure to release, and performance tuning of Redis to maintain high concurrency.
At the end, a promotional banner for a PHP training course is displayed, offering links to frontend, PHP, and e‑commerce practical stages.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
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.