1. 升级Laravel与PHP版本
使用Laravel的最新稳定版本(如2025年推荐的10.x),新版本通常包含性能改进、安全修复及更高效的代码逻辑;同时升级PHP至8.1及以上版本(推荐8.2),PHP 8的JIT编译器和性能优化能显著提升脚本执行速度。
2. 优化PHP配置
php.ini中设置:opcache.enable=1、opcache.memory_consumption=128(内存大小根据服务器调整)、opcache.max_accelerated_files=10000(加速文件数量)、opcache.revalidate_freq=60(缓存验证频率,单位秒)。xdebug,仅在开发环境使用),减少内存占用。memory_limit(如生产环境设为512M或1G),避免过高消耗服务器资源。3. 配置Web服务器(Nginx/Apache)
server {
listen 80;
server_name yourdomain.com;
root /path/to/laravel/public;
index index.php index.html;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
fastcgi_pass unix:/var/run/php/php8.2-fpm.sock;
fastcgi_index index.php;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
location ~ /\.ht {
deny all;
}
}
mod_rewrite(用于URL重写)和mod_deflate(压缩输出),并在虚拟主机配置中添加:<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/plain text/css application/javascript application/json
</IfModule>
4. 数据库性能优化
users.email、orders.user_id)添加索引,避免全表扫描。例如:Schema::table('users', function (Blueprint $table) {
$table->index('email');
});
with()方法预加载关联数据,避免N+1查询问题。例如:$users = User::with('posts')->get(); // 一次性加载用户及关联的文章
Cache::remember()缓存频繁查询的结果(如商品分类、热门文章),减少数据库负载。例如:$data = Cache::remember('hot_articles', 3600, function () {
return Article::where('is_hot', 1)->orderBy('created_at', 'desc')->get();
});
5. 利用缓存提升性能
.env中设置:CACHE_DRIVER=redis,并配置Redis连接(config/cache.php和config/database.php)。location ~* \.(jpg|jpeg|png|gif|css|js)$ {
expires 30d;
add_header Cache-Control "public, no-transform";
}
php artisan route:cache
php artisan config:cache
6. 异步处理耗时任务(队列系统)
.env中设置:QUEUE_CONNECTION=redis。php artisan make:job ProcessPodcast生成任务类,在handle()方法中编写耗时逻辑(如发送邮件、处理图片)。例如:class SendEmailJob implements ShouldQueue {
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public function handle() {
Mail::to($this->email)->send(new WelcomeMail());
}
}
dispatch(new SendEmailJob($email))分发任务;使用Supervisor守护queue:work进程,确保任务持续执行。例如Supervisor配置:[program:laravel_queue]
command=php /path/to/laravel/artisan queue:work --daemon --tries=3
autostart=true
autorestart=true
user=www-data
numprocs=4
redirect_stderr=true
stdout_logfile=/path/to/laravel/storage/logs/queue.log
7. 代码与查询优化
select()明确指定所需字段(避免select *),减少数据传输量。例如:$users = User::select('id', 'name', 'email')->get();
load()方法按需加载关联数据,避免不必要的查询。例如:$user = User::find(1);
$user->load('posts'); // 仅在需要时加载文章
insertGetId()批量插入数据,减少数据库交互次数。例如:User::insert([
['name' => 'John', 'email' => 'john@example.com'],
['name' => 'Jane', 'email' => 'jane@example.com']
]);
8. 监控与持续优化
error),避免日志文件过大占用磁盘空间。例如:'log' => 'error',