1. 系统级基础优化
ulimit -n 65535临时设置,永久生效需修改/etc/security/limits.conf(添加* soft nofile 65535、* hard nofile 65535)。/etc/sysctl.conf,添加net.core.somaxconn = 65535(最大连接队列长度)、net.ipv4.tcp_max_syn_backlog = 65535(SYN队列长度)、net.ipv4.tcp_tw_reuse = 1(复用TIME-WAIT连接),执行sysctl -p使配置生效。2. PHP环境配置优化
php.ini(如/etc/php/8.2/fpm/php.ini),设置:opcache.enable=1
opcache.enable_cli=1
opcache.memory_consumption=512
opcache.interned_strings_buffer=64
opcache.max_accelerated_files=10000
opcache.revalidate_freq=60
opcache.fast_shutdown=1
重启PHP-FPM(systemctl restart php8.2-fpm)使配置生效。/etc/php/8.2/fpm/pool.d/www.conf,调整进程管理参数:listen = /var/run/php/php8.2-fpm.sock
listen.owner = www-data
listen.group = www-data
pm = dynamic
pm.max_children = 50 # 根据服务器内存调整(如4GB内存可设为50)
pm.start_servers = 10
pm.min_spare_servers = 5
pm.max_spare_servers = 20
重启PHP-FPM使配置生效。3. Laravel框架自身优化
.env文件,设置APP_ENV=production、APP_DEBUG=false,禁用调试模式以减少不必要的性能开销。php artisan config:cache
php artisan route:cache
php artisan view:cache
(注:开发环境禁用此功能,避免配置修改不生效。)--optimize-autoloader生成更高效的自动加载文件,减少类加载时间:composer install --optimize-autoloader --no-dev
生产环境部署时务必添加--no-dev排除开发依赖。4. 数据库性能优化
EXPLAIN分析慢查询,为WHERE、JOIN、ORDER BY等关键字段添加索引(如Schema::table('users')->index('email'));避免SELECT *,只查询所需字段;使用with()预加载关联数据,解决N+1查询问题(如User::with('posts')->get())。/etc/mysql/mysql.conf.d/mysqld.cnf,优化InnoDB缓冲池(占内存70%-80%)、日志文件大小等参数:[mysqld]
innodb_buffer_pool_size = 4G # 根据服务器内存调整(如8GB内存设为4G)
innodb_log_file_size = 512M
innodb_flush_log_at_trx_commit = 2 # 平衡性能与数据安全性(生产环境建议设为1)
query_cache_size = 64M
query_cache_type = 1
重启MySQL(systemctl restart mysql)使配置生效。CACHE_DRIVER=redis、SESSION_DRIVER=redis),缓存频繁访问的查询结果(如热门文章、配置信息),降低数据库负载。5. 队列与异步处理
QUEUE_CONNECTION=redis),创建作业类(php artisan make:job ProcessPodcast),并通过dispatch()分发任务。/etc/supervisor/conf.d/laravel-worker.conf,配置command=php /var/www/laravel/artisan queue:work redis --tries=3,并设置autostart=true、autorestart=true)。6. Web服务器配置优化
try_files指令将请求转发给PHP-FPM:server {
listen 80;
server_name example.com;
root /var/www/laravel/public;
index index.php index.html;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php8.2-fpm.sock;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
location ~ /\.ht {
deny all;
}
}
测试配置(nginx -t)后重启Nginx(systemctl restart nginx)。gzip on; gzip_types text/plain text/css application/json application/javascript;,减少传输数据量,提升页面加载速度。7. 高级性能加速工具
composer require laravel/octane
php artisan octane:start --server=swoole
配置Nginx反向代理到Octane(如fastcgi_pass http://127.0.0.1:8000)。composer require laravel/telescope);Blackfire用于深度性能分析(composer require blackfire/blackfire),定位代码瓶颈(如慢查询、内存泄漏)。