Laravel 项目使用 Octane 加速
Jul 19, 2021
Laravel 项目使用 Octane 加速
安装 Octane
需要先使用 PHP8.0+的版本,才能正常安装。
$ composer require laravel/octane
$ php artisan octane:install
如果选择的是 swoole
来做 server
,那么需要 php 先安装swoole
扩展
$ pecl install swoole
如果选择的是 roadrunner
做 server
,那么需要下载它的二进制文件,该二进制文件是由Go语言
构建的,当第一次基于 roadrunner
启动时,octane
将会自动下载并安装该二进制文件。
在安装过程中,遇到下载错误
这个是有 github
的请求频率限流导致的异常,需要到 https://github.com/settings/tokens
中将自己的 token 导出到环境变量中。
$ export GITHUB_TOKEN=你的token
重新执行 php artisan octane:install
,成功了
将目标 server
添加到 .env
文件中
OCTANE_SERVER=roadrunner
使用 octane
启动项目
$ php artisan octane:start
成功。
线上部署
Nginx
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
server {
listen 80;
listen [::]:80;
server_name 域名;
server_tokens off;
root 你的目录;
index index.php;
charset utf-8;
location /index.php {
try_files /not_exists @octane;
}
location / {
try_files $uri $uri/ @octane;
}
location = /favicon.ico { access_log off; log_not_found off; }
location = /robots.txt { access_log off; log_not_found off; }
access_log off;
error_log off;
error_page 404 /index.php;
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;
}
}
Supervisor
Laravel Octane
虽然提供了 start 命令用于启动 Server,但该命令只能在前台运行(不支持 -d);在部署到生产环境时,常见的办法还是利用 Supervisor 来进行进程管理
参考模板
[program:你的程序名]
process_name=%(program_name)s_%(process_num)02d
command=/usr/bin/php /data/www/your_project/artisan octane:start --host=127.0.0.1 --port=8000
autostart=true
autorestart=true
user=root
numprocs=1
redirect_stderr=true
stdout_logfile=/data/www/your_project/storage/logs/octane-worker.log
修改模板,将其对应的变量修改成自己项目的,将文件复制到 /etc/supervisor/conf
目录下
$ cp xx /etc/supervisor/conf
$ supervisorctl reread
$ supervisorctl update
$ supervisorctl start your_program_name: