分类 所有文章 下的文章 - 空痕博客
首页
小记
php
python
uni
机器人
QQ机器人
APP
KHMD
KHMD-v3
其他页面
友情链接
用户留言
联系空痕
热门文章
企鹅音乐歌单链接获取教程
网易云音乐歌单链接获取教程
空痕音乐下载器
酷我音乐歌单链接获取教程
酷狗歌单码获取
标签搜索
KHMD
uniapp
APP
空痕音乐下载器
PHP
KongHen
机器人
QQ
音乐
音源
QQ音乐
UTS
ID3
python
pyinstaller
redis
发布
登录
找到
14
篇与
相关的结果
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
3天前
0
0
0
2024-12-02
UTS封装uni.request请求拦截器
UTS封装请求拦截器主要就是数据类型的问题 简单封装示例:每次请求在请求头中携带设备信息 /** * 封装请求体携带设备信息 * 说明:header携带设备信息 * * 作者:KongHen02 */ export type RequestParams = { url: string; method: RequestMethod; data?: string; header?: UTSJSONObject; timeout?: number; sslVerify?: boolean; withCredentials?: boolean; firstIpv4?: boolean; } export type RequestRoot = { code: number; msg: string; data?: any } export type RequestRes = { data?: any; error?: string; } // 获取系统信息 export const getSystemInfo = (): string => { const system = uni.getSystemInfoSync() // 返回app信息,依次为appid,系统名称,系统版本,app版本,设备id,使用____分割 return system.appId + "____" + system.osName + "____" + system.osVersion + "____" + system.appVersionCode + "____" + system.deviceId } // 发送请求并携带设备信息 export const sendRequest = (options: RequestParams): Promise<RequestRes> => { let info = getSystemInfo(); let header = {} if (options.header != null) { header = UTSJSONObject.assign(options.header as UTSJSONObject, { app: info }) }else { header = UTSJSONObject.assign(header, { app: info }) } // 返回一个Promise return new Promise((resolve, reject) => { uni.request<RequestRoot>({ // ...options, // 展开其他请求配置 url: options.url, method: options.method, data: options.data ?? "", header: header, timeout: options.timeout ?? 6000, sslVerify: options.sslVerify ?? true, withCredentials: options.withCredentials ?? false, firstIpv4: options.firstIpv4 ?? false, success: (res) => { const data = res.data as RequestRoot if(data.code == 200) { // 在请求成功时解析Promise resolve({ data: data.data } as RequestRes) }else { uni.showToast({ title: data.msg, icon: "error" }) reject({ error: data['msg'] as string } as RequestRes) } }, fail: (err) => { uni.showToast({ title: err.errMsg, icon: "error" }) // 在请求失败时拒绝Promise reject({ error: err.errMsg as string } as RequestRes) } } as RequestOptions<any>); }); } 使用示例 // 导入封装的函数 import { sendRequest } from "@/common/request.uts" // 定义存储的变量 // 1. 数组 const list = ref<UTSJSONObject[]>([]) // 2. 对象 // const list = ref<UTSJSONObject>({}) // 请求示例:使用Promise的方式调用sendRequest函数 sendRequest({ url: 'https://api.example.com/data', method: 'GET' }).then(res => { // 处理请求成功的结果 list.value = res.data as UTSJSONObject[] // 数组,对应的存储数组的变量 // list.value = res.data as UTSJSONObject // 对象,对应的存储对象的变量 console.log('处理结果:', data.value); }).catch(err => { // 处理请求失败的情况 console.error('请求失败:', err); }) 在模板中使用示例 注意使用变量中数据的方法只能为下标[""]方法,.操作符不可以,会报错 <view v-for="item in noticeList" :key="item['id']"> <image mode="widthFix" :src="item['image']"></image> <view> <text>{{ item['title'] }}</text> <text>{{ item['sort'] }}</text> </view> </view>说明: 因为书写习惯原因,我自己的所有后端返回数据均为json,返回对象参数如下 参数描述示例code错误码200: 成功, 400: 失败, 或其他msg请求结果说明请求成功/请求失败等data请求返回的结果json数组/对象示例如下: data为数组 { code: 200, msg: "请求成功", data: [] } data为对象 { code: 200, msg: "请求成功", data: {} } 对应封装的请求中的自定义类型RootRes(request.uts文件中)
所有文章
uts
KongHen02
1年前
0
1
0
2024-06-18
酷狗歌单码获取
酷狗歌单图片
所有文章
空痕音乐下载器
KongHen02
1年前
5
6,143
34
2024-06-05
PHP封装功能较全CURL函数
经常用到,之前一直重复写,今天写脚本的时候就封装了一个,方便重复利用 <?php /** * httpRequest * 发送curl请求 * * @param string $url 请求的URL * @param string $method 请求方法,默认是'GET' * @param string $back 返回类型,默认为空,可以为'all'或'cookie' * @param array $params 请求参数,默认为空数组 * @param array $headers 请求头,默认为空数组 * @return array 响应数据 * */ function sendCurlRequest($url, $method = 'GET', $back = "", $params = [], $headers = []) { // 初始化cURL会话 $ch = curl_init(); // 设置请求URL if ($method == 'GET' && !empty($params)) { $url .= '?' . http_build_query($params); } curl_setopt($ch, CURLOPT_URL, $url); // 设置请求方法 if($method == 'POST') { curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params)); } // 返回而不是输出内容 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 允许跟随重定向 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // 设置返回类型 if ($back === "all") { // 设置为true以包含响应头 curl_setopt($ch, CURLOPT_HEADER, true); // 设置为false以包含响应体 curl_setopt($ch, CURLOPT_NOBODY, false); } elseif ($back === "cookie") { // 设置为true以包含响应头 curl_setopt($ch, CURLOPT_HEADER, true); } // 设置请求头 if (!empty($headers)) { curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); } // 设置超时(可选) curl_setopt($ch, CURLOPT_TIMEOUT, 30); // 执行cURL会话 $response = curl_exec($ch); // 获取HTTP状态码 $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); // 获取错误信息 $error = curl_error($ch); // 处理cookie $cookies = []; if ($back == "cookie" || $back == "all") { // 分离头部和主体 $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE); $header = substr($response, 0, $header_size); if ($back == "all") { $body = substr($response, $header_size); } // 解析头部中的Cookie preg_match_all('/^Set-Cookie:\s*([^;]*)/mi', $header, $matches); foreach ($matches[1] as $item) { parse_str($item, $cookie); $cookies = array_merge($cookies, $cookie); } } // 关闭cURL会话 curl_close($ch); // 构建返回数据 if ($error) { $data = ['code' => 400, 'msg' => $error]; } else if ($httpCode >= 400) { $data = ['code' => 400, 'msg' => "HTTP error $httpCode"]; } else if ($back == "all") { $data = ['code' => 200, 'cookie' => $cookies, 'body' => $body]; } else if ($back == "cookie") { $data = ['code' => 200, 'cookie' => $cookies]; } else { $data = ['code' => 200, 'body' => $response]; } // 返回响应数据 return $data; }
所有文章
PHP
KongHen02
1年前
0
158
0
2024-04-09
网易云音乐歌单链接获取教程
网易歌单上限1000 1图片
所有文章
空痕音乐下载器
KongHen02
1年前
19
31,130
168
1
2
3
下一页
易航博客