124 lines
2.9 KiB
PHP
124 lines
2.9 KiB
PHP
<?php
|
|
|
|
namespace app\common\server;
|
|
|
|
/**
|
|
* Class RedisHelper
|
|
*
|
|
* 这是一个用于操作 Redis 的帮助类,提供了基本的 Redis 操作方法。
|
|
*/
|
|
class ConfigRedisHelper
|
|
{
|
|
/**
|
|
* @var \Redis Redis 实例(静态属性)
|
|
*/
|
|
private static $redis;
|
|
|
|
/**
|
|
* 获取 Redis 实例
|
|
*
|
|
* @return \Redis
|
|
*/
|
|
public function getRedis()
|
|
{
|
|
if (self::$redis === null) {
|
|
// 从环境变量中获取 Redis 主机和端口,默认为 127.0.0.1 和 6379
|
|
$host = env('configredis.host', '127.0.0.1');
|
|
$port = env('configredis.port', '6379');
|
|
// 从环境变量中获取 Redis 数据库编号,默认为 0
|
|
$db = env('configredis.db', '0');
|
|
// 创建 Redis 实例
|
|
self::$redis = new \Redis();
|
|
// 连接到 Redis 服务器
|
|
$this->connect($host, $port);
|
|
// 选择数据库
|
|
self::$redis->select((int)$db);
|
|
}
|
|
|
|
return self::$redis;
|
|
}
|
|
|
|
/**
|
|
* 连接到 Redis 服务器
|
|
*
|
|
* @param string $host Redis 主机
|
|
* @param int $port Redis 端口
|
|
* @return bool
|
|
*/
|
|
private function connect($host, $port)
|
|
{
|
|
return self::$redis->connect($host, (int)$port);
|
|
}
|
|
|
|
/**
|
|
* 从 Redis 中获取指定键的值
|
|
*
|
|
* @param string $key 键名
|
|
* @return mixed 键对应的值
|
|
*/
|
|
public function get($key)
|
|
{
|
|
return $this->getRedis()->get($key);
|
|
}
|
|
|
|
/**
|
|
* 设置指定键的值,并可选设置过期时间(默认 600 秒)
|
|
*
|
|
* @param string $key 键名
|
|
* @param mixed $value 键值
|
|
* @param int $timeout 过期时间(秒)
|
|
* @return bool 设置是否成功
|
|
*/
|
|
public function set($key, $value, $timeout = 600)
|
|
{
|
|
if ($timeout > 0) {
|
|
return $this->getRedis()->setex($key, $timeout, $value);
|
|
}
|
|
return $this->getRedis()->set($key, $value);
|
|
}
|
|
|
|
/**
|
|
* 删除指定键
|
|
*
|
|
* @param string $key 键名
|
|
* @return int 被删除的键的数量
|
|
*/
|
|
public function delete($key)
|
|
{
|
|
return $this->getRedis()->del($key);
|
|
}
|
|
|
|
/**
|
|
* 检查指定键是否存在
|
|
*
|
|
* @param string $key 键名
|
|
* @return bool 键是否存在
|
|
*/
|
|
public function exists($key)
|
|
{
|
|
return $this->getRedis()->exists($key);
|
|
}
|
|
|
|
/**
|
|
* 设置指定键的过期时间
|
|
*
|
|
* @param string $key 键名
|
|
* @param int $timeout 过期时间(秒)
|
|
* @return bool 设置是否成功
|
|
*/
|
|
public function expire($key, $timeout)
|
|
{
|
|
return $this->getRedis()->expire($key, $timeout);
|
|
}
|
|
|
|
/**
|
|
* 选择 Redis 数据库
|
|
*
|
|
* @param int $db 数据库编号
|
|
* @return bool 选择是否成功
|
|
*/
|
|
public function select($db)
|
|
{
|
|
return $this->getRedis()->select($db);
|
|
}
|
|
} |