标签 PHP 下的文章 - 空痕博客
首页
小记
php
python
uni
机器人
QQ机器人
APP
KHMD
KHMD-v3
其他页面
友情链接
用户留言
联系空痕
热门文章
企鹅音乐歌单链接获取教程
网易云音乐歌单链接获取教程
空痕音乐下载器
酷我音乐歌单链接获取教程
酷狗歌单码获取
标签搜索
KHMD
uniapp
APP
空痕音乐下载器
PHP
KongHen
机器人
QQ
音乐
音源
QQ音乐
UTS
ID3
python
pyinstaller
redis
发布
登录
找到
1
篇与
相关的结果
2025-02-20
php利用redis实现接口数据缓存
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); ?>
所有文章
PHP
# PHP
# redis
KongHen02
2天前
0
0
0
易航博客