Laravel 提供了强大的缓存系统,支持多种缓存驱动: - 文件缓存 - 数据库缓存 - Redis/Memcached - APCu - DynamoDB - 数组缓存(仅用于测试)
问题表现: - 写入缓存时报权限错误 - 缓存文件无法生成
解决方案:
# 确保 storage 目录有正确权限
sudo chown -R www-data:www-data /path/to/laravel/storage
sudo chmod -R 775 /path/to/laravel/storage
问题表现: - Redis 连接超时 - 缓存读取失败
解决方案: 1. 确保 Redis 服务已安装并运行:
sudo apt-get install redis-server
sudo systemctl enable redis
sudo systemctl start redis
.env
文件:CACHE_DRIVER=redis
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
问题表现: - PHP 执行速度慢 - 代码更改后不生效
解决方案: 1. 安装 OPcache:
sudo apt-get install php-opcache
/etc/php/7.x/fpm/php.ini
:opcache.enable=1
opcache.enable_cli=1
opcache.memory_consumption=128
opcache.interned_strings_buffer=8
opcache.max_accelerated_files=4000
opcache.revalidate_freq=60
手动清理缓存命令:
# 清除应用缓存
php artisan cache:clear
# 清除视图缓存
php artisan view:clear
# 清除路由缓存
php artisan route:clear
# 清除配置缓存
php artisan config:clear
设置定时任务自动清理缓存:
crontab -e
添加以下内容(每天凌晨3点清理):
0 3 * * * cd /path-to-your-project && php artisan cache:clear >> /dev/null 2>&1
生产环境配置:
php artisan config:cache
php artisan route:cache
监控工具:
php artisan cache:stats
查看缓存统计队列处理: 对于耗时的缓存操作,使用队列系统:
Cache::remember('key', $minutes, function() {
return SomeHeavyOperation::dispatch()->onQueue('cache');
});
错误:无法写入缓存
df -h
错误:Redis 连接失败
systemctl status redis
redis-cli ping
错误:缓存不更新
php artisan optimize:clear
通过以上方案,可以有效解决 Laravel 在 Linux 环境下的各种缓存问题,并优化应用性能。