在 Ubuntu 下,让 ThinkPHP(以 ThinkPHP 5 / 6 为主,也适用于 8)使用 Redis,一般按下面步骤来即可。
sudo apt update
sudo apt install redis-server
sudo systemctl start redis
sudo systemctl enable redis
redis-cli ping
# 返回 PONG 表示正常
先确认你的 PHP 版本(如 7.4 / 8.1):
php -v
安装对应扩展:
sudo apt install php-redis
# 或指定版本,例如:
sudo apt install php8.1-redis
# 如果是 Nginx + PHP-FPM
sudo systemctl restart php8.1-fpm
sudo systemctl restart nginx
# 如果是 Apache
sudo systemctl restart apache2
php -m | grep redis
看到 redis 即成功。
编辑:
config/cache.php
示例:
return [
'default' => 'redis',
'stores' => [
'redis' => [
'type' => 'redis',
'host' => '127.0.0.1',
'port' => 6379,
'password' => '',
'select' => 0,
'timeout' => 0,
'persistent' => false,
],
],
];
编辑:
application/config.php
'cache' => [
'type' => 'redis',
'host' => '127.0.0.1',
'port' => 6379,
'password' => '',
'select' => 0,
'expire' => 0,
'prefix' => '',
],
use think\facade\Cache;
// 写入
Cache::set('name', 'thinkphp', 3600);
// 读取
echo Cache::get('name');
// 删除
Cache::delete('name');
use think\facade\Cache;
$redis = Cache::store('redis')->handler();
$redis->set('test', 'hello');
echo $redis->get('test');
// config/session.php
return [
'type' => 'redis',
'host' => '127.0.0.1',
'port' => 6379,
'password' => '',
'select' => 1,
];
redis-server 是否运行bind 127.0.0.1 是否限制# redis.conf
requirepass yourpassword
ThinkPHP 对应填写 password
如果你用的是 ThinkPHP 5 / 6 / 8 的具体版本,或者 用的是 Docker / LNMP,我可以给你更精确的配置示例。