Swoole HTTP的應用

概述

我們都知道HTTP是一種協議,允許WEB服務器和瀏覽器通過互聯網進行發送和接受數據。
想對HTTP進行詳細的瞭解,可以找下其他文章,這篇文章不多做介紹。
我們在網上能看到的界面,圖片,動畫,音頻,視頻等,都有依賴這個協議的。
在做WEB系統的時候,都使用過IIS,Apache,Nginx吧,我們利用Swoole也可以簡單的實現一個WEB服務器。
主要使用了HTTP的兩個大對象:Request請求對象,Response響應對象。
請求,包括GET,POST,COOKIE,Header等。
響應,包括狀態,響應體,擴展,發送文件等。

 

不多說,先分享兩個程序:

  • 一,實現一個基礎的Demo:“你好,Swoole。”

     

  • 二,實現一個簡單的路由控制
本地版本:
  • PHP 7.2.6

  • 旋風4.3.1

代碼

一,Demo:“你好,Swoole。”
示例效果:
備註: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  -- 代碼根目錄
│ ├─ 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'

 

 

擴展

  • 可以試着上傳文件,做一個小的FTP服務器。

  • 可以學習Swoole開源框架:EasySwoole,Swoft,One。

  • 可以將Swoole整合到當前正在使用的PHP框架中。

我的官方羣點擊此處加入羣聊【PHP/web/高級學習交流羣】,一起學習,相互討論。

羣內已經有管理將知識體系整理好(源碼,學習視頻等資料),歡迎加羣免費領取

 

這套精品PHP教程絕不是市場上的那些妖豔賤貨可比,作爲web開發的佼佼者PHP並不遜色其他語言,加上Swoole後更加是如虎添翼!進軍通信 、物聯網行業開發百度地圖、百度訂單中心、虎牙、戰旗TV等!寒冬裁員期過後正是各大企業擴大招人的時期,現在市場初級程序員氾濫,進階中高級程序員絕對是各大企業急需的人才,這套學習教程適合那些1-5年以內的PHP開發者正處於瓶頸期,想要突破自己進階中高級、架構師!名額有限,先到先得!

騰訊T3-T4標準精品PHP架構師教程目錄大全,只要你看完保證薪資上升一個臺階(持續更新)​

部分資料截圖:

還有限時精品福利:

★騰訊高級PHP工程師筆試題目

★億級PV高併發場景訂單的處理

★laravel開發天貓商城組件服務

★戰旗TV視頻直播的架構項目實戰

掃描下面二維碼領取

 

對PHP後端技術,對PHP架構技術感興趣的朋友,我的官方羣點擊此處,一起學習,相互討論。

羣內已經有管理將知識體系整理好(源碼,學習視頻等資料),歡迎加羣免費領取。

本課程深度對標騰訊T3-T4標準,貼身打造學習計劃爲web開發人員進階中高級、架構師提升技術,爲自己增值漲薪!加入BAT特訓營還可以獲得內推大廠名額以及GO語言學習權限!!!


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章