Laravel 在 Debian 上運行緩慢可能是由于多種原因造成的,以下是一些常見的優化和加速方法:
Octane 是一個高性能的 Laravel 服務器,可以通過使用高能應用服務器(如 FrankenPHP、Open Swoole、Swoole 和 RoadRunner)來提高應用程序的性能。以下是啟用 Octane 的步驟:
安裝 Octane:
composer require laravel/octane
安裝服務(以 FrankenPHP 為例):
php artisan octane:install --server=frankenphp
啟用服務:
php artisan octane:start
配置 Nginx: 修改 Nginx 配置文件,將請求代理給 Octane 服務。例如:
location /index.php {
try_files /not_exists @octane;
}
location / {
try_files $uri $uri/ @octane;
}
location @octane {
set $suffix "";
if ($uri = /index.php) {
set $suffix?%query_string;
}
proxy_http_version 1.1;
proxy_set_header Host $http_host;
proxy_set_header Scheme $scheme;
proxy_set_header SERVER_PORT $server_port;
proxy_set_header REMOTE_ADDR $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
proxy_pass http://127.0.0.1:8000$suffix;
}
確保 PHP 配置文件(php.ini)中的設置是優化的。例如:
內存限制:增加內存限制。
memory_limit = 256M
最大執行時間:增加最大執行時間。
max_execution_time = 300
OPcache:啟用 OPcache 擴展。
zend_extension=opcache.so
opcache.enable=1
opcache.validate_timestamps=1
opcache.fast_shutdown=1
確保 Nginx 和 PHP-FPM 配置正確。以下是一個基本的配置示例:
Nginx 配置:
server {
listen 80;
server_name example.com;
root /var/www/example/public;
index index.php index.html index.htm;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
}
location ~ /\.ht {
deny all;
}
}
PHP-FPM 配置:
[www]
listen = 127.0.0.1:9000
listen.owner = www-data
listen.group = www-data
user = www-data
group = www-data
pm = dynamic
pm.max_children = 5
pm.start_servers = 2
pm.min_spare_servers = 1
pm.max_spare_servers = 3
安裝并配置 Redis 作為 Laravel 的緩存驅動:
安裝 Redis:
sudo apt install redis-server
配置 Laravel:
在 .env 文件中配置 Redis 緩存驅動:
CACHE_DRIVER=redis
SESSION_DRIVER=redis
確保數據庫查詢是優化的??梢允褂?Laravel 的 Eloquent ORM 的 Eager Loading 功能來減少 N+1 查詢問題。
使用 Supervisor 來管理 PHP-FPM 進程,確保服務在后臺穩定運行:
安裝 Supervisor:
sudo apt install supervisor
配置 Supervisor:
創建 Supervisor 配置文件 /etc/supervisor/conf.d/php7.4-fpm.conf:
[program:php7.4-fpm]
process_name=%(program_name)s
command=/usr/sbin/php7.4-fpm7.4 -F
autostart=true
autorestart=true
user=www-data
redirect_stderr=true
stdout_logfile=/var/log/php7.4-fpm.log
重啟 Supervisor:
sudo service supervisor restart
通過以上步驟,可以顯著提高 Laravel 在 Debian 上的運行速度。根據具體情況,可能需要進一步調整和優化。