在 Linux 下使用 Laravel 缓存,其实和操作系统关系不大,主要是 Laravel 的缓存配置和使用方式。下面从「配置 → 使用 → 常见缓存驱动」一步步说明。
Laravel 缓存配置在:
config/cache.php
默认缓存驱动在 .env 中设置:
CACHE_DRIVER=file
常见可选值:
file(默认,文件缓存)redismemcacheddatabasearray(仅请求生命周期内)适合:
配置:
CACHE_DRIVER=file
缓存目录:
storage/framework/cache
使用:
use Illuminate\Support\Facades\Cache;
// 写入缓存
Cache::put('name', 'Laravel', 600); // 10分钟
// 读取
$name = Cache::get('name');
// 判断是否存在
Cache::has('name');
// 删除
Cache::forget('name');
// 清空
Cache::flush();
sudo apt update
sudo apt install redis-server
启动:
sudo systemctl start redis
sudo systemctl enable redis
sudo apt install php-redis
重启 PHP:
sudo systemctl restart php-fpm
# 或
sudo systemctl restart apache2
.env
CACHE_DRIVER=redis
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
Cache::put('user:1', $user, 3600);
Cache::get('user:1');
适合: 不想装 Redis,但想集中管理
php artisan cache:table
php artisan migrate
CACHE_DRIVER=database
安装:
sudo apt install memcached php-memcached
配置:
CACHE_DRIVER=memcached
// 永久缓存
Cache::forever('key', 'value');
// 获取或写入
$value = Cache::remember('key', 600, function () {
return DB::table('users')->get();
});
// 自增
Cache::increment('count');
// 原子锁(Redis)
Cache::lock('lock')->get(function () {
// 业务逻辑
});
如果报错:
Permission denied in storage/framework/cache
解决:
sudo chown -R www-data:www-data storage
sudo chmod -R 755 storage
(用户可能是 nginx 或 apache)
✅ Redis + Linux + Laravel
如果你愿意,可以告诉我:
我可以给你一套最合适的 Laravel 缓存方案。