Deploy: 2026-05-23 00:24:51

This commit is contained in:
Hamza-Ayed
2026-05-23 00:24:52 +03:00
parent 408b4b0048
commit 0e16fd3f5d
3 changed files with 39 additions and 4 deletions

View File

@@ -32,5 +32,7 @@ REDIS_ENABLED=false
REDIS_HOST=127.0.0.1
REDIS_PORT=6379
REDIS_PASSWORD=
REDIS_DB=0

View File

@@ -35,6 +35,7 @@ class Cache
$host = Env::get('REDIS_HOST', '127.0.0.1');
$port = (int)Env::get('REDIS_PORT', 6379);
$password = Env::get('REDIS_PASSWORD', null);
$db = (int)Env::get('REDIS_DB', 0);
// Connect with 1.0s timeout to prevent request blocking
$connected = $redis->connect($host, $port, 1.0);
@@ -43,10 +44,14 @@ class Cache
return null;
}
if (!empty($password)) {
if ($password !== null && $password !== '' && strtolower($password) !== 'null') {
$redis->auth($password);
}
if ($db > 0) {
$redis->select($db);
}
self::$client = $redis;
} catch (\Exception $e) {
error_log('[Cache Error] Redis connection error: ' . $e->getMessage());
@@ -56,6 +61,14 @@ class Cache
return self::$client;
}
/**
* Helper to get prefixed key
*/
private static function getPrefixedKey(string $key): string
{
return 'nabeh:' . $key;
}
/**
* Retrieve cache item by key.
*/
@@ -67,7 +80,8 @@ class Cache
}
try {
$value = $client->get($key);
$prefixedKey = self::getPrefixedKey($key);
$value = $client->get($prefixedKey);
return $value !== false ? json_decode($value, true) : null;
} catch (\Exception $e) {
error_log('[Cache Error] Redis get failed: ' . $e->getMessage());
@@ -86,7 +100,8 @@ class Cache
}
try {
return $client->setex($key, $ttl, json_encode($value));
$prefixedKey = self::getPrefixedKey($key);
return $client->setex($prefixedKey, $ttl, json_encode($value));
} catch (\Exception $e) {
error_log('[Cache Error] Redis set failed: ' . $e->getMessage());
return false;
@@ -104,7 +119,8 @@ class Cache
}
try {
return $client->del($key) > 0;
$prefixedKey = self::getPrefixedKey($key);
return $client->del($prefixedKey) > 0;
} catch (\Exception $e) {
error_log('[Cache Error] Redis delete failed: ' . $e->getMessage());
return false;

View File

@@ -61,6 +61,23 @@ if (class_exists('\Redis')) {
} else {
echo " ❌ Failed to get correct value from Redis.\n";
}
// Verify prefixing using a direct native Redis connection
$nativeRedis = new \Redis();
try {
if ($nativeRedis->connect(Env::get('REDIS_HOST', '127.0.0.1'), (int)Env::get('REDIS_PORT', 6379), 1.0)) {
$nativeVal = $nativeRedis->get('nabeh:test_cache_key');
if ($nativeVal) {
echo " ✅ Verified Prefixing: Native Redis key 'nabeh:test_cache_key' exists and has value: " . $nativeVal . "\n";
} else {
echo " ❌ Prefixing test failed: key not found in native Redis.\n";
}
$nativeRedis->close();
}
} catch (\Exception $ex) {
echo " Native verification connection skipped/failed: " . $ex->getMessage() . "\n";
}
Cache::delete('test_cache_key');
} else {
echo " Redis server is not running or unreachable (Fallback triggered, test completed successfully).\n";