ThinkPHP使用Redis
前置环境
安装Redis
新建一个ThinkPHP6项目
ThinkPHP使用Redis
安装 Redis 扩展
# 在项目目录下执行如下代码,安装redis依赖
composer require topthink/think-redis
config/database.php
<?php
// +----------------------------------------------------------------------
// | 缓存设置
// +----------------------------------------------------------------------
return [
// 默认缓存驱动
'default' => env('cache.driver', 'redis'),
// 缓存连接方式配置
'stores' => [
'file' => [
// 驱动方式
'type' => 'File',
// 缓存保存目录
'path' => '',
// 缓存前缀
'prefix' => '',
// 缓存有效期 0表示永久缓存
'expire' => 0,
// 缓存标签前缀
'tag_prefix' => 'tag:',
// 序列化机制 例如 ['serialize', 'unserialize']
'serialize' => [],
],
// redis缓存
'redis' => [
// 驱动方式
'type' => 'redis',
// 服务器地址
'host' => '127.0.0.1',
],
// 更多的缓存连接
],
];
测试Redis
<?php
namespace app\controller;
use think\facade\Cache;
use think\facade\Db;
class Index
{
public function index()
{
// 写入缓存
Cache::store('redis')->set('name', 'value');
// 从缓存中读取
$name = Cache::store('redis')->get('name');
// 使用 Redis 实例
$redis = Cache::store('redis')->handler();
// 使用 Redis 实例进行操作
$redis->set('foo', 'bar');
$value = $redis->get('foo');
// 使用 Redis 作为数据库驱动
$data = Db::connect('redis')->table('user')->where('id', 1)->find();
return 'Hello, ' . $name;
}
}
检查问题
1.确保已经正确安装和启用了 PHP Redis 扩展,可以通过运行 php -m | grep redis 命令来检查是否加载了 Redis 扩展。
2.检查 config/cache.php 文件中是否正确配置了 Redis 缓存存储器,并确保有名为 "redis" 的存储器配置项。
3.确保在 config/cache.php 文件中启用了 Redis 缓存存储器。
如果这篇文章对你有用,可以关注本人微信公众号获取更多ヽ(^ω^)ノ ~