在 CentOS 上优化 Laravel 性能,可以从系统层、PHP 层、Laravel 层、缓存与数据库、Web 服务器几个维度来做。下面给你一套比较实用、可落地的方案。
Laravel 对 PHP 版本敏感,尽量使用 PHP 8.1 / 8.2 / 8.3
php -v
如版本过低,建议通过 remi 源升级:
yum install -y epel-release
yum install -y https://rpms.remirepo.net/enterprise/remi-release-7.rpm
yum-config-manager --enable remi-php82
yum install -y php php-cli php-fpm php-mysqlnd php-mbstring php-xml php-curl
编辑 PHP 配置:
vi /etc/php.d/10-opcache.ini
示例配置:
opcache.enable=1
opcache.memory_consumption=256
opcache.interned_strings_buffer=16
opcache.max_accelerated_files=10000
opcache.revalidate_freq=60
opcache.validate_timestamps=0
生产环境建议
validate_timestamps=0
重启 PHP-FPM:
systemctl restart php-fpm
APP_ENV=production
APP_DEBUG=false
php artisan config:cache
php artisan route:cache
php artisan view:cache
php artisan optimize
部署后修改代码必须重新执行
middleware__construct 里查数据库ServiceProvider 里做重逻辑.env:
CACHE_DRIVER=redis
SESSION_DRIVER=redis
QUEUE_CONNECTION=redis
安装 Redis:
yum install -y redis
systemctl enable redis
systemctl start redis
cache()with())User::with('posts')->get();
location ~ \.php$ {
fastcgi_pass unix:/run/php-fpm/www.sock;
fastcgi_index index.php;
include fastcgi_params;
}
gzip on;
gzip_types text/css application/javascript application/json;
location /static/ {
expires 30d;
access_log off;
}
编辑:
vi /etc/php-fpm.d/www.conf
示例(4 核 8G):
pm = dynamic
pm.max_children = 100
pm.start_servers = 20
pm.min_spare_servers = 10
pm.max_spare_servers = 30
重启:
systemctl restart php-fpm
php artisan queue:work --daemon
用 supervisor 守护:
yum install -y supervisor
* * * * * php /path/artisan schedule:run
top / htopphp-fpm 慢日志laravel-debugbar(开发)opcache on
config:cache
route:cache
view:cache
redis cache
nginx gzip
php-fpm tuned
queue used
如果你愿意,可以告诉我:
我可以给你一套定制化参数。