PHP 优化
php.ini
配置:
ini
opcache.enable=1
opcache.memory_consumption=256
opcache.max_accelerated_files=20000
opcache.validate_timestamps=0 # 生产环境设为0,开发环境设为1
realpath_cache_size=4096K
realpath_cache_ttl=600
Web 服务器优化
nginx
gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
fastcgi_cache_path /var/run/nginx-cache levels=1:2 keys_zone=LARAVEL:100m inactive=60m;
fastcgi_cache_key "$scheme$request_method$host$request_uri";
数据库优化
ini
innodb_buffer_pool_size = 4G # 根据服务器内存调整
innodb_log_file_size = 256M
query_cache_size = 0 # Laravel 有更好的缓存机制
路由缓存
php artisan route:cache
配置缓存
php artisan config:cache
视图缓存
php artisan view:cache
优化 Composer 自动加载
composer dump-autoload --optimize
使用队列处理耗时任务
Eloquent 优化
select()
指定需要的字段with()
预加载关联关系chunk()
或 cursor()
缓存策略
php
$value = Cache::remember('users', $seconds, function () {
return DB::table('users')->get();
});
前端优化
使用 Laravel Octane
composer require laravel/octane
php artisan octane:start --server=swoole --port=8000
使用 Horizon 管理队列
composer require laravel/horizon
php artisan horizon
监控与日志
数据库读写分离
config/database.php
中的读写分离分库分表
静态缓存
图像优化
通过以上优化组合,可以显著提升 Laravel 应用的性能。建议从服务器配置开始,逐步实施代码层面的优化,并使用监控工具验证优化效果。