在 Linux + Laravel 环境下,缓存一般指的是 Laravel 的缓存系统。Laravel 本身已经封装得非常好,你只需要选择“缓存驱动”并合理使用 API 即可。
下面从 概念 → 配置 → 常见用法 → Linux 实战建议 逐步说明。
Laravel 支持多种缓存驱动(在 config/cache.php 中配置):
| 驱动 | 说明 | 适合场景 |
|---|---|---|
| file | 文件缓存(默认) | 开发、小型项目 |
| database | 数据库缓存 | 已有数据库,不想装额外服务 |
| redis | Redis 缓存 | 生产环境推荐 |
| memcached | Memcached | 高性能场景 |
| array | 内存(请求级) | 测试 |
| apc / apcu | PHP 扩展 | 单机 |
✅ 生产环境最推荐:Redis
# Ubuntu / Debian
sudo apt update
sudo apt install redis-server
# 启动
sudo systemctl enable redis
sudo systemctl start redis
测试:
redis-cli ping
# 返回 PONG
sudo apt install php-redis
sudo systemctl restart php-fpm # 或 apache2
.env 文件:
CACHE_DRIVER=redis
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
清空配置缓存:
php artisan config:clear
use Illuminate\Support\Facades\Cache;
// 永久缓存
Cache::forever('site_name', 'Laravel');
// 缓存 10 分钟
Cache::put('user_count', 100, 10);
$name = Cache::get('site_name');
// 带默认值
$count = Cache::get('user_count', 0);
if (Cache::has('user_count')) {
//
}
Cache::forget('user_count');
Cache::flush(); // 清空所有缓存(慎用)
$users = Cache::remember('users', 60, function () {
return DB::table('users')->get();
});
✅ 第一次查数据库
✅ 之后 60 分钟内直接读缓存
public function index()
{
return Cache::remember('api.posts', 30, function () {
return Post::latest()->paginate(10);
});
}
composer require spatie/laravel-model-status
或使用:
composer require genealabs/laravel-model-caching
# 清缓存(非常重要)
php artisan cache:clear
php artisan config:clear
php artisan route:clear
php artisan view:clear
# 查看 Redis 缓存
redis-cli
keys *
✅ 使用 Redis
✅ 设置缓存过期时间
✅ 不缓存用户敏感信息
✅ 部署后执行 php artisan cache:clear
✅ 用 Supervisor 管理队列 + 缓存
你可以告诉我:
我可以直接给你 可复制的 Laravel 缓存代码示例。