在 Linux 环境下使用 Laravel 配置缓存,主要涉及 配置文件、缓存驱动选择、以及常用命令。下面按“由浅入深”的方式说明。
Laravel 的缓存配置位于:
config/cache.php
关键配置项:
'default' => env('CACHE_DRIVER', 'file'),
'stores' => [
'file' => [
'driver' => 'file',
'path' => storage_path('framework/cache/data'),
],
'redis' => [
'driver' => 'redis',
'connection' => 'default',
],
// memcached / database / array 等
],
编辑项目根目录的 .env 文件:
CACHE_DRIVER=file
常见可选值:
file(默认,最简单)redis(生产推荐)memcacheddatabasearray(仅请求生命周期)无需额外安装,确保目录可写:
chmod -R 755 storage
chown -R www-data:www-data storage
sudo apt install redis-server
sudo systemctl enable redis
sudo systemctl start redis
sudo apt install php-redis
sudo systemctl restart php-fpm # 或 apache2
CACHE_DRIVER=redis
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
创建缓存表:
php artisan cache:table
php artisan migrate
.env:
CACHE_DRIVER=database
# 清空所有缓存
php artisan cache:clear
# 清空配置缓存
php artisan config:clear
# 清空路由缓存
php artisan route:clear
# 清空视图缓存
php artisan view:clear
# 缓存配置(生产环境)
php artisan config:cache
php artisan route:cache
php artisan view:cache
use Illuminate\Support\Facades\Cache;
// 写入
Cache::put('key', 'value', 600); // 10分钟
// 读取
$value = Cache::get('key');
// 永久
Cache::forever('key', 'value');
// 删除
Cache::forget('key');
✅ 使用 Redis
✅ 使用 config:cache
✅ 确保 storage 目录权限正确
✅ 不要使用 array 驱动
如果你愿意,可以告诉我:
我可以给你一套完整可直接用的配置方案。