php利用redis实现服务端数据缓存。
要求php版本大于8.0
缓存类
文件RedisCache.php
<?php
/**
* 请求缓存类
* 利用redis实现数据缓存
*
* 作者:KongHen02
*
*/
class RedisCache
{
private string $key;
private Redis $redis;
public function __construct(int $db = 0, bool $device = false) {
$config = [
'host' => '127.0.0.1',
'port' => 6379,
'timeout' => 2,
'database' => $db
];
try {
$this->redis = new Redis();
$this->redis->connect(
$config['host'],
$config['port'],
$config['timeout']
);
$this->redis->select($config['database']);
} catch (RedisException $e) {
error_log("Redis连接失败: " . $e->getMessage());
throw new RuntimeException("缓存服务不可用");
}
$this->key = $this->generateKey($device);
}
public function getCache(): mixed
{
try {
header('X-Cache: ' . ($this->redis->exists($this->key) ? 'HIT' : 'MISS'));
$data = $this->redis->get($this->key);
return $data !== false ? unserialize($data) : null;
} catch (RedisException $e) {
error_log("读取缓存数据失败: " . $e->getMessage());
return null;
}
}
public function setCache(mixed $data, int $ttl = 7200): bool
{
try {
return $this->redis->setex(
$this->key,
$ttl,
serialize($data)
);
} catch (RedisException $e) {
error_log("写入缓存数据失败: " . $e->getMessage());
return false;
}
}
public function __destruct()
{
try {
$this->redis?->close();
} catch (RedisException $e) {
error_log("关闭Redis连接失败: " . $e->getMessage());
}
}
private function generateKey(bool $device): string
{
$url = $_SERVER['HTTP_HOST'];
$urlArray = explode("?", $_SERVER['REQUEST_URI']);
$url .= $urlArray[0];
$params = $_POST;
ksort($params);
$keyParts = [
$_SERVER['REQUEST_METHOD'],
$device ? $this->detectDevice() : null,
$url,
substr(md5($urlArray[1]), 0, 8),
substr(md5(http_build_query($params)), 0, 8)
];
return implode(':', array_filter($keyParts));
}
private function detectDevice(): string
{
$ua = strtolower($_SERVER['HTTP_USER_AGENT'] ?? '');
return match(true) {
(bool)preg_match('/mobile|android|iphone|ipod|windows phone/', $ua) => 'mobile',
(bool)preg_match('/tablet|ipad|kindle/', $ua) => 'tablet',
default => 'desktop'
};
}
}
?>
使用说明
<?php
// 导入缓存类
require_once($_SERVER['DOCUMENT_ROOT'] . "/RedisCache.php");
try {
// 0:redis表序;0-15;必填
// true:是否区分客户端类型(手机/平板/电脑);true/false(默认);可空
$RedisCache = new RedisCache(0, true);
if (($result = $RedisCache->getCache()) !== null) {
exit($result);
}
} catch (RuntimeException $e) {
// 缓存服务不可用时继续执行
header('X-Cache-Status: Down');
}
// 业务逻辑处理
$result = "数据内容,不限制类型";
// 缓存成功结果
if (isset($result)) {
// $result:需要缓存的数据;mixed;必填
// 7200:数据有效期;int(默认7200);可空
$RedisCache?->setCache($result, 7200);
}
echo($result);
?>