Using Laravel's RedisLock to Prevent Cache Breakdown
This article explains the cache breakdown problem, introduces Laravel 7's built‑in RedisLock class, details its constructor parameters, and provides a complete code example demonstrating how to acquire and release a Redis lock to safely populate and update cached data.
Cache breakdown occurs when a cached item expires, many concurrent requests miss the cache, and simultaneously query the database, causing a sudden spike in database load.
Using a Redis lock is an effective way to mitigate this issue. Laravel 7 includes the \Illuminate\Cache\RedisLock class, which can be instantiated directly.
The constructor of RedisLock is defined as:
/**
* @param \Illuminate\Redis\Connections\Connection $redis redis instance
* @param string $name redis lock key name
* @param int $seconds redis lock expiration time
* @param string|null $owner redis lock value; if null, a random string is generated
*/
public function __construct($redis, $name, $seconds, $owner = null)
{
parent::__construct($name, $seconds, $owner);
$this->redis = $redis;
}After creating a RedisLock object, you can call acquire() to obtain an exclusive lock and release() to free it.
Example usage:
use Illuminate\Support\Facades\Redis;
use Illuminate\Cache\RedisLock;
function RedisLockTest()
{
// Get Redis instance
$redis = Redis::connection();
$key = 'redis_test_key';
// Create RedisLock instance
$redisLock = new RedisLock($redis, $key . '_lock', 30);
$res = $redis->get($key);
if (empty($res)) {
// Try to acquire lock
if ($redisLock->acquire()) {
// Simulate fetching data from database
sleep(5);
$value = date('Y-m-d H:i:s');
// Update cache (expire in 60 seconds)
$redis->setex($key, 60, $value);
// Release lock
$redisLock->release();
return $value;
} else {
// Wait and retry
sleep(2);
return RedisLockTest();
}
} else {
return $res;
}
}This pattern ensures that only one request populates the cache while others wait, preventing the database from being overwhelmed during high concurrency scenarios.
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.
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.
