Larave|Lumen 配合Swoole 加速
Larave|Lumen 配合Swoole 加速:
PHP的生命周期,当你每次运行PHP脚本的时候,PHP都需要初始化模块并为你的运行环境启动Zend引擎,中间会经过语法分析、词法分析,最后把你的代码编译为OpCode来交给Zend引擎执行。 但是,这样的生命周期需要在每次请求的时候都执行一遍,因为单个请求创建的环境在请求执行结束之后会立即销毁。 换句话说,在传统的PHP生命周期中,为了脚本执行而浪费了大量的时间去创建和销毁资源。想象一下Laravel这样的框架,在每次请求中需要加载多少文件?同时也需要大量的I/O操作。这将花费大量的时间。
因此如果可以利用swoole内置一个应用级别的Server,并且所有的脚本文件在加载一次之后便可以保存在内存中,那性能会有很大的提升。 Swoole可以提供强大性能而Laravel则可以提供优雅的代码结构。
使用composer安装swooletw插件
composer require swooletw/laravel-swoole
然后添加服务提供者:
一、如果使用的Laravel,在config/app.php 服务提供者数组中添加该服务提供者: 生成配置文件
php artisan vendor:publish --tag=laravel-swoole
[
'providers' => [
SwooleTW\Http\LaravelServiceProvider::class,
],
]
二、使用 Lumen
$app->register(SwooleTW\Http\LumenServiceProvider::class);
然后将包中的配置文件发布到 app/config 中 //config下生成swoole_http.conf和swoole_websocket.php以及routes下websocket.php
php artisan vendor:publish
启动swoole直接对外服务
php artisan swoole:http start
Starting swoole http server...
Swoole http server started: <http://127.0.0.1:1215>
然后可以通过 http://127.0.0.1:1215 来访问项目,但实际上线后将使用域名。
所以我们可以通过使用nginx代理对外服务(推荐这种) 在项目配置文件中加上这段代码
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
然后在项目伪静态替换为这段代码
location / {
try_files $uri $uri/ @swoole;
}
location @swoole {
set $suffix "";
if ($uri = /index.php) {
set $suffix ?$query_string;
}
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;
# IF https
# proxy_set_header HTTPS "on";
proxy_pass http://127.0.0.1:1215$suffix;
}
完整配置
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
server {
listen 80;
server_name your.domain.com;
root /path/to/laravel/public;
index index.php;
location = /index.php {
# Ensure that there is no such file named "not_exists"
# in your "public" directory.
try_files /not_exists @swoole;
}
# any php files must not be accessed
#location ~* \.php$ {
# return 404;
#}
location / {
try_files $uri $uri/ @swoole;
}
location @swoole {
set $suffix "";
if ($uri = /index.php) {
set $suffix ?$query_string;
}
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;
# IF https
# proxy_set_header HTTPS "on";
proxy_pass http://127.0.0.1:1215$suffix;
}
配置完成后可直接通过域名访问。
最后说一下在使用中遇到的问题: PHP中的超全局变量无法使用 $_POST $_GET $_SERVER $_FILES $_COOKIE $_REQUEST 推荐通过 Illuminate\Http\Request 对象来获取请求信息
参考:链接