Files
urukprize/backend/core/RedisClient.php
T

86 lines
2.4 KiB
PHP

<?php
declare(strict_types=1);
namespace Core;
use Redis;
use Throwable;
class RedisClient
{
private static ?Redis $instance = null;
private static bool $connectionFailed = false;
private function __construct() {}
private function __clone() {}
public static function getInstance(): ?Redis
{
if (self::$connectionFailed) {
return null;
}
if (self::$instance === null) {
if (!class_exists('Redis')) {
self::$connectionFailed = true;
return null;
}
try {
$config = require __DIR__ . '/../config/redis.php';
$redis = new Redis();
$connected = $redis->connect($config['host'], $config['port'], (float)$config['timeout']);
if ($connected) {
if (!empty($config['password'])) {
$redis->auth($config['password']);
}
if (!empty($config['database'])) {
$redis->select((int)$config['database']);
}
$redis->setOption(Redis::OPT_PREFIX, $config['prefix']);
self::$instance = $redis;
} else {
self::$connectionFailed = true;
}
} catch (Throwable $e) {
self::$connectionFailed = true;
error_log('[Redis Error] ' . $e->getMessage());
return null;
}
}
return self::$instance;
}
public static function get(string $key): ?string
{
$redis = self::getInstance();
if (!$redis) return null;
$val = $redis->get($key);
return $val !== false ? (string)$val : null;
}
public static function set(string $key, string $value, int $ttlSeconds = 0): bool
{
$redis = self::getInstance();
if (!$redis) return false;
return $ttlSeconds > 0 ? (bool)$redis->setex($key, $ttlSeconds, $value) : (bool)$redis->set($key, $value);
}
public static function del(string $key): bool
{
$redis = self::getInstance();
if (!$redis) return false;
return (bool)$redis->del($key);
}
public static function has(string $key): bool
{
$redis = self::getInstance();
if (!$redis) return false;
return (bool)$redis->exists($key);
}
}