在 Linux + Laravel 环境下,实现缓存一般分三步:配置缓存驱动 → 使用缓存 API → 可选安装缓存服务(如 Redis)。下面按常见场景说明。
Laravel 默认支持:
file(默认,文件缓存)redis(最常用)memcacheddatabasearray(仅当前请求).env
CACHE_DRIVER=file
默认缓存目录:
storage/framework/cache
use Illuminate\Support\Facades\Cache;
// 写入缓存
Cache::put('name', 'Laravel', 600); // 10分钟
// 读取
$name = Cache::get('name');
// 永久缓存
Cache::forever('site', 'example.com');
// 删除
Cache::forget('name');
sudo apt update
sudo apt install redis-server
启动:
sudo systemctl start redis
sudo systemctl enable redis
sudo apt install php-redis
sudo systemctl restart apache2 # 或 php-fpm
.env
CACHE_DRIVER=redis
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
Cache::put('user_1', $user, 3600);
$user = Cache::get('user_1');
php artisan cache:table
php artisan migrate
CACHE_DRIVER=database
// 不存在才写入
Cache::add('key', 'value', 600);
// 获取或回调
$value = Cache::remember('users', 600, function () {
return DB::table('users')->get();
});
// 清空缓存
php artisan cache:clear
✅ 使用 Redis
✅ 设置合理过期时间
✅ 避免缓存大对象
✅ 用 remember 减少数据库压力
如果你愿意,可以告诉我:
我可以直接给你一套完整配置方案。