天天看點

Swoole HTTP 的應用

目錄

  • 概述
  • 代碼
  • 小結
  • 擴充

這是關于 Swoole 學習的第四篇文章:Swoole HTTP 的應用。

  • 第三篇:Swoole WebSocket 的應用
  • 第二篇:Swoole Task 的應用
  • 第一篇:Swoole Timer 的應用

我們都知道 HTTP 是一種協定,允許 WEB 伺服器和浏覽器通過網際網路進行發送和接受資料。

想對 HTTP 進行詳細的了解,可以找下其他文章。

我們在網上能看到的界面,圖檔,動畫,音頻,視訊 等,都有依賴這個協定的。

在做 WEB 系統的時候,都使用過 IIS、Apache、Nginx 吧,我們利用 Swoole 也可以 簡單的實作一個 WEB 伺服器。

主要使用了 HTTP 的兩大對象:Request 請求對象、Response 響應對象。

Request,包括 GET、POST、COOKIE、Header等。

Response,包括 狀态、響應體、跳轉、發送檔案等。

不多說,分享兩個程式:

  • 一、實作一個基礎的 Demo:“你好,Swoole.”
  • 二、實作一個簡單的 路由控制

本地版本:

  • PHP 7.2.6
  • Swoole 4.3.1

一、Demo:“你好,Swoole.”

示例效果:

Swoole HTTP 的應用

備注:IP 位址是我的虛拟機。

示例代碼:

<?php

class Server
{
    private $serv;

    public function __construct() {
        $this->serv = new swoole_http_server("0.0.0.0", 9502);
        $this->serv->set([
            'worker_num'      => 2, //開啟2個worker程序
            'max_request'     => 4, //每個worker程序 max_request設定為4次
            'daemonize'       => false, //守護程序(true/false)
        ]);

        $this->serv->on('Start', [$this, 'onStart']);
        $this->serv->on('WorkerStart', [$this, 'onWorkStart']);
        $this->serv->on('ManagerStart', [$this, 'onManagerStart']);
        $this->serv->on("Request", [$this, 'onRequest']);

        $this->serv->start();
    }

    public function onStart($serv) {
        echo "#### onStart ####".PHP_EOL;
        echo "SWOOLE ".SWOOLE_VERSION . " 服務已啟動".PHP_EOL;
        echo "master_pid: {$serv->master_pid}".PHP_EOL;
        echo "manager_pid: {$serv->manager_pid}".PHP_EOL;
        echo "########".PHP_EOL.PHP_EOL;
    }

    public function onManagerStart($serv) {
        echo "#### onManagerStart ####".PHP_EOL.PHP_EOL;
    }

    public function onWorkStart($serv, $worker_id) {
        echo "#### onWorkStart ####".PHP_EOL.PHP_EOL;
    }

    public function onRequest($request, $response) {
        $response->header("Content-Type", "text/html; charset=utf-8");
        $html = "<h1>你好 Swoole.</h1>";
        $response->end($html);
    }
}

$server = new Server();
           

二、路由控制

Swoole HTTP 的應用

目錄結構:

├─ swoole_http  -- 代碼根目錄
│  ├─ server.php
│  ├─ controller
│     ├── Index.php
│     ├── Login.php
           

server.php

<?php

class Server
{
    private $serv;

    public function __construct() {
        $this->serv = new swoole_http_server("0.0.0.0", 9501);
        $this->serv->set([
            'worker_num'      => 2, //開啟2個worker程序
            'max_request'     => 4, //每個worker程序 max_request設定為4次
            'document_root'   => '',
            'enable_static_handler' => true,
            'daemonize'       => false, //守護程序(true/false)
        ]);

        $this->serv->on('Start', [$this, 'onStart']);
        $this->serv->on('WorkerStart', [$this, 'onWorkStart']);
        $this->serv->on('ManagerStart', [$this, 'onManagerStart']);
        $this->serv->on("Request", [$this, 'onRequest']);

        $this->serv->start();
    }

    public function onStart($serv) {
        echo "#### onStart ####".PHP_EOL;
        swoole_set_process_name('swoole_process_server_master');

        echo "SWOOLE ".SWOOLE_VERSION . " 服務已啟動".PHP_EOL;
        echo "master_pid: {$serv->master_pid}".PHP_EOL;
        echo "manager_pid: {$serv->manager_pid}".PHP_EOL;
        echo "########".PHP_EOL.PHP_EOL;
    }

    public function onManagerStart($serv) {
        echo "#### onManagerStart ####".PHP_EOL.PHP_EOL;
        swoole_set_process_name('swoole_process_server_manager');
    }

    public function onWorkStart($serv, $worker_id) {
        echo "#### onWorkStart ####".PHP_EOL.PHP_EOL;
        swoole_set_process_name('swoole_process_server_worker');

        spl_autoload_register(function ($className) {
            $classPath = __DIR__ . "/controller/" . $className . ".php";
            if (is_file($classPath)) {
                require "{$classPath}";
                return;
            }
        });
    }

    public function onRequest($request, $response) {
        $response->header("Server", "SwooleServer");
        $response->header("Content-Type", "text/html; charset=utf-8");
        $server = $request->server;
        $path_info    = $server['path_info'];
        $request_uri  = $server['request_uri'];

        if ($path_info == '/favicon.ico' || $request_uri == '/favicon.ico') {
            return $response->end();
        }

        $controller = 'Index';
        $method     = 'home';


        if ($path_info != '/') {
            $path_info = explode('/',$path_info);
            if (!is_array($path_info)) {
                $response->status(404);
                $response->end('URL不存在');
            }

            if ($path_info[1] == 'favicon.ico') {
                return;
            }

            $count_path_info = count($path_info);
            if ($count_path_info > 4) {
                $response->status(404);
                $response->end('URL不存在');
            }

            $controller = (isset($path_info[1]) && !empty($path_info[1])) ? $path_info[1] : $controller;
            $method = (isset($path_info[2]) && !empty($path_info[2])) ? $path_info[2] : $method;
        }

        $result = "class 不存在";

        if (class_exists($controller)) {
            $class = new $controller();
            $result = "method 不存在";
            if (method_exists($controller, $method)) {
                $result = $class->$method($request);
            }
        }

        $response->end($result);
    }
}

$server = new Server();
           

Index.php

<?php

class Index
{
    public function home($request)
    {
        $get = isset($request->get) ? $request->get : [];

        //@TODO 業務代碼

        $result = "<h1>你好,Swoole。</h1>";
        $result.= "GET參數:".json_encode($get);
        return $result;
    }
}
           

Login.php

<?php

class Login
{
    public function index($request)
    {
        $post = isset($request->post) ? $request->post : [];

        //@TODO 業務代碼

        return "<h1>登入成功。</h1>";
    }
}
           

一、Swoole 可以替代 Nginx 嗎?

暫時不能,随着 Swoole 越來越強大,以後說不準。

官方建議 Swoole 與 Nginx 結合使用。

Http\Server 對 Http 協定的支援并不完整,建議僅作為應用伺服器。并且在前端增加Nginx作為代理。

根據自己的 Nginx 配置檔案,可以自行調整。

比如:新增一個配置檔案

enable-swoole-php.conf

location ~ [^/]\.php(/|$)
{
    proxy_http_version 1.1;
    proxy_set_header Connection "keep-alive";
    proxy_set_header X-Real-IP $remote_addr;
    proxy_pass http://127.0.0.1:9501;
}
           

我們都習慣會将虛拟域名的配置檔案放在 vhost 檔案夾中。

比如,虛拟域名的配置檔案為:local.swoole.com.conf,可以選擇加載 enable-php.conf ,也可以選擇加載 enable-swoole-php.conf。

配置檔案供參考:

server
    {
        listen 80;
        #listen [::]:80;
        server_name local.swoole.com ;
        index index.html index.htm index.php default.html default.htm default.php;
        root  /home/wwwroot/project/swoole;

        #include rewrite/none.conf;
        #error_page   404   /404.html;

        #include enable-php.conf;
        include enable-swoole-php.conf;

        location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$
        {
            expires      30d;
        }

        location ~ .*\.(js|css)?$
        {
            expires      12h;
        }

        location ~ /.well-known {
            allow all;
        }

        location ~ /\.
        {
            deny all;
        }

        access_log  /home/wwwlogs/local.swoole.com.log;
    }
           

如果直接編輯 server 段的代碼也是可以的。

二、修改了 controller 檔案夾中的業務代碼,每次都是重新開機服務才生效嗎?

不是,每次重新開機服務會影響到正常使用者使用的,正常處理的請求會被強制關閉。

在本地運作路由的代碼時,試試這個指令:

ps aux | grep swoole_process_server_master | awk '{print $2}' | xargs kill -USR1
           

給 master 程序發送一個 USR1 的信号,當 Swoole Server 接到這個信号後,就會讓所有 worker 在處理完目前的請求後,進行重新開機。

如果檢視所有的程序,試試這個指令:

ps -ef | grep 'swoole_process_server' | grep -v 'grep'
           

需要文章中源碼的,關注公衆号,回複“swoole http”即可。

  • 可以試着上傳檔案,做一個小的FTP伺服器。
  • 可以試着整合到目前正在使用的PHP架構中。
  • 可以學習一些Swoole開源架構:EasySwoole、Swoft、One。

本文歡迎轉發,轉發請注明作者和出處,謝謝!

Swoole HTTP 的應用

作者:新亮筆記(關注公衆号,可申請添加微信好友)

出處:https://www.cnblogs.com/xinliangcoder

本文版權歸作者和部落格園共有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文連接配接,否則保留追究法律責任的權利。

繼續閱讀