ThinkPHP 5.1 配置 Redis 缓存需三步:启用 phpredis 扩展、安装 think-redis 包、正确配置 cache.php;任一缺失将静默回退 file 驱动,导致 Cache::get() 返回 null。

ThinkPHP 5.1 配置 Redis 缓存,核心是三件事:装对扩展、写对配置、验得真实——少一个环节,缓存就静默退回到 file 驱动,Cache::get() 返回 null 也查不出错。
确认 PHP 已启用 phpredis 扩展
TP5.1 不兼容 Predis 或纯 PHP 实现,必须用原生 C 扩展 phpredis。 执行命令检查: ```bash php -m | grep redis ``` 如果无输出,说明未启用: - Linux/macOS:在 `php.ini` 中添加 `extension=redis.so`,然后重启 PHP-FPM 或 Apache/Nginx - Windows:下载对应 PHP 版本的 `php_redis.dll`,放入 `ext/` 目录,在 `php.ini` 中加 `extension=php_redis.dll`⚠️ 注意:改完 php.ini 后必须重启服务,否则配置不生效。
安装官方 Redis 适配包(非可选)
TP5.1 默认不内置 Redis 驱动类,需手动引入: ```bash composer require topthink/think-redis ``` 该包提供 `think\cache\driver\Redis` 类,并自动注册服务(无需手动调用 `register()`)。 验证是否装好:检查 `vendor/topthink/think-redis/src/` 下是否存在 `Redis.php` 和 `Provider.php`。修改 config/cache.php 配置项
TP5.1 支持「单一驱动」和「复合驱动」两种模式,推荐按以下方式配置:-
若只用 Redis(最简):
return [ 'type' => 'redis', 'host' => '127.0.0.1', 'port' => 6379, 'password' => '', // 空密码也必须显式写 '' 'select' => 0, // 必须是整数,不能是字符串 "0" 'prefix' => 'tp51:', 'expire' => 3600, 'timeout' => 3, ]; -
若同时支持多种缓存(如 file + redis),用复合模式:
立即学习“PHP免费学习笔记(深入)”;
return [ 'type' => 'complex', 'default' => ['type' => 'file'], 'redis' => [ 'type' => 'redis', 'host' => '127.0.0.1', 'port' => 6379, 'password' => '', 'select' => 0, 'prefix' => 'tp51:', 'expire' => 3600, ], ];⚠️ 关键点:
-
'default' => 'redis'这行必须加上(若用复合模式),否则默认走 file -
select字段类型必须为int,写成'select' => "0"会导致连接失败 -
password即使为空,也得写'',不能省略或写null
-
快速验证 Redis 是否真正生效
别信配置文件写了就通,终端实测最可靠: ```bash # 写入缓存(10秒后过期) php -r "var_dump(cache('test_key', 'hello_redis', 10));"立即读取
php -r "var_dump(cache('test_key'));"
✅ 正确结果:两次都输出 `string(11) "hello_redis"` ❌ 错误表现:第二次输出 `NULL` → 说明仍在 fallback 到 file 驱动,回头检查 `default` 值、`stores.redis` 是否存在、`phpredis` 是否启用 也可以进 Redis 控制台确认: ```bash redis-cli > keys "tp51:*" # 应能看到刚写的 key > get "tp51:test_key"
不复杂但容易忽略。



















