使用swoole来加速你的laravel应用

2 篇文章 0 订阅
2 篇文章 0 订阅
  • 为什么要用swoole来加速laravel呢?

下图展示了PHP的生命周期,正如你所看到的那样,当你每次运行PHP脚本的时候,PHP都需要初始化模块并为你的运行环境启动Zend引擎,中间会经过语法分析、词法分析,最后把你的代码编译为OpCode来交给Zend引擎执行。

但是,这样的生命周期需要在每次请求的时候都执行一遍,因为单个请求创建的环境在请求执行结束之后会立即销毁。

换句话说,在传统的PHP生命周期中,为了脚本执行而浪费了大量的时间去创建和销毁资源。想象一下Laravel这样的框架,在每次请求中需要加载多少文件?同时也需要大量的I/O操作。这将花费大量的时间。

                                    

因此如果我们利用swoole内置一个应用级别的Server,并且所有的脚本文件在加载一次之后便可以保存在内存中,那性能会有很大的提升。Swoole可以提供强大性能而Laravel则可以提供优雅的代码结构,这俩真是完美组合。

 

  • 安装

首先需要安装swoole扩展,具体可参考我的另一篇文章   链接

使用composer安装swooletw插件

composer require swooletw/laravel-swoole

然后添加服务提供者:

如果你使用的Laravel,在config/app.php 服务提供者数组中添加该服务提供者:

[
    'providers' => [
        SwooleTW\Http\LaravelServiceProvider::class,
    ],
]

如果你使用的Lumen,请将下面的代码加到bootstrap/app.php

$app->register(SwooleTW\Http\LumenServiceProvider::class);

将包中的配置文件发布到 app/config 中

//config下生成swoole_http.conf和swoole_websocket.php以及routes下websocket.php
php artisan vendor:publish --tag=laravel-swoole
  • 启动

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 来访问的你laravel应用。

 

 

使用nginx代理对外服务(推荐这种)

nginx配置

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 对象来获取请求信息

 

 

 

 

 

 

  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值