I'm using Laravel's cache system with Redis (using the phpredis driver) and encountered a puzzling issue: when I call $connection->del($key), the key is not deleted, but it works when I use executeRaw(['DEL', $key]).
This is my setup:
- Laravel version: 10.0.3
- Redis client: phpredis
- Redis version: 7.4.1
- Cache prefix: laravel_cache_solar_cache
I have the following key stored in Redis:
laravel_cache_solar_cache:v1/verticals-menu:userId:4:b6f331f8f609d4bf3e9f4568bd69aacba4e464aa
Attempting deletion with the Redis connection:
does not remove the key. However, using executeRaw bypasses this problem:
$connection->executeRaw(['DEL', $key]);
Also, Cache::delete($key) works but isn't suitable in our clustered setup.
This is how my Redis connection is initialized:
foreach ($this->clusterConnectionNames as $clusterConnectionName) {
try {
$this->logService->info("Processing crossClusterFlushByKeys for cluster '$clusterConnectionName'");
$store = Cache::store($clusterConnectionName)->getStore();
$connection = $store->connection();
// Retrieve Redis prefixes from configuration
$prefix = Config::get('database.redis.options.prefix');
$cachePrefix = $store->getPrefix();
$scanPatternBase = $prefix . $cachePrefix;
// Initialize a counter for the total number of keys deleted in this cluster
$totalDeleted = 0;
foreach ($keysForDeletion as $baseKey) {
$matchPattern = $scanPatternBase . $baseKey . "*";
$cursor = null;
do {
$scanResult = $connection->scan($cursor, [
'match' => $matchPattern,
'count' => 1000
]);
if ($scanResult === false) {
$this->logService->warning("SCAN command failed for pattern '$matchPattern' on cluster '$clusterConnectionName'");
break;
}
[$cursor, $matches] = $scanResult;
if (!empty($matches)) {
$this->logService->info("Deleting " . count($matches) . " keys from cluster '$clusterConnectionName'", [
'keys' => $matches
]);
foreach ($matches as $key) {
$connection->executeRaw(['DEL', $key]);
}
}
} while ($cursor != 0);
}
$this->logService->info("Total keys deleted from cluster '$clusterConnectionName': $totalDeleted");
} catch (Exception $e) {
// Handle exception
$this->logService->error("Error: " . $e->getMessage());
}
}
The deletion works flawlessly with executeRaw, but using $connection->del($key) fails to remove the key.