tp6使用redis缓存数据直接存储json格式解决方案!需要自取!
最近在搞自己的开源的博客,用的是tp6框架,因为今年大环境整体都不好,本身我离职的,闲暇时间比较多,想着闲着也是闲着,搞就认认真真搞一下,所以博客就决定增加redis缓存支持,然后看了下tp6的缓存文档,看到评论区有一个大哥一个问题问的挺好的,整哈我自己也遇到了类似的问题,记录一下解决方案!
相关链接
- tp6缓存文档:https://www.kancloud.cn/manual/thinkphp6_0/1037634
- 大哥的疑惑(如下图所示)
实现效果
实现步骤
参考代码
<?php
// 缓存服务编码函数
if (!function_exists("cache_encode")) {
function cache_encode($data)
{
return json_encode($data);
}
}
// 缓存服务解码函数
if (!function_exists("cache_decode")) {
function cache_decode($data)
{
return json_decode($data, true);
}
}
2023年9月4日 补充
tp8 cache.php 配置参考
<?php
// +----------------------------------------------------------------------
// | 缓存设置
// +----------------------------------------------------------------------
return [
// 默认缓存驱动
'default' => env('cache_engine', 'file'),
// 缓存连接方式配置
'stores' => [
'file' => [
// 驱动方式
'type' => 'File',
// 缓存保存目录
'path' => '',
// 缓存前缀
'prefix' => '',
// 缓存有效期 0表示永久缓存
'expire' => 0,
// 缓存标签前缀
'tag_prefix' => 'tag:',
// 序列化机制 例如 ['serialize', 'unserialize']
'serialize' => [],
],
'redis' => [
'type' => 'redis',
'host' => env('redis_host', '127.0.0.1'),
'port' => env('redis_port', '6379'),
'password' => env('redis_password', ''),
'select' => env('redis_select', '0'),
'expire' => (int)env('redis_expire', '0'),
'prefix' => env('redis_prefix', ''),
'timeout' => (int)env('redis_timeout', '0'),
'serialize' => ['cache_encode', 'cache_decode']
]
],
];
tp8 common.php 参考
<?php
// 缓存服务编码函数
if (!function_exists("cache_encode")) {
function cache_encode($data): bool|string
{
return json_encode($data, JSON_UNESCAPED_UNICODE);
}
}
// 缓存服务解码函数
if (!function_exists("cache_decode")) {
function cache_decode($data): array
{
return json_decode($data, true);
}
}
tp8 env 配置参考
APP_DEBUG = true
DB_TYPE = mysql
DB_HOST = 127.0.0.1
DB_NAME = example
DB_USER = root
DB_PASS = 123456
DB_PORT = 3306
DB_CHARSET = utf8mb4
CACHE_ENGINE = redis
REDIS_HOST = 127.0.0.1
REDIS_PORT = 6379
REDIS_PASSWORD = 123456
DEFAULT_LANG = zh-cn