Swoole HTTP 的应用

2019年4月26日 369点热度 0人点赞 0条评论

第 80 篇文章

这是关于 Swoole 学习的第四篇文章:Swoole HTTP 的应用。

概述

我们都知道 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.”

示例效果:

图片

备注:IP 地址是我的虚拟机。

示例代码:

  1. <?php


  2. class Server

  3. {

  4. private $serv;


  5. public function __construct() {

  6. $this->serv = new swoole_http_server("0.0.0.0", 9502);

  7. $this->serv->set([

  8. 'worker_num' => 2, //开启2个worker进程

  9. 'max_request' => 4, //每个worker进程 max_request设置为4次

  10. 'daemonize' => false, //守护进程(true/false)

  11. ]);


  12. $this->serv->on('Start', [$this, 'onStart']);

  13. $this->serv->on('WorkerStart', [$this, 'onWorkStart']);

  14. $this->serv->on('ManagerStart', [$this, 'onManagerStart']);

  15. $this->serv->on("Request", [$this, 'onRequest']);


  16. $this->serv->start();

  17. }


  18. public function onStart($serv) {

  19. echo "#### onStart ####".PHP_EOL;

  20. echo "SWOOLE ".SWOOLE_VERSION . " 服务已启动".PHP_EOL;

  21. echo "master_pid: {$serv->master_pid}".PHP_EOL;

  22. echo "manager_pid: {$serv->manager_pid}".PHP_EOL;

  23. echo "########".PHP_EOL.PHP_EOL;

  24. }


  25. public function onManagerStart($serv) {

  26. echo "#### onManagerStart ####".PHP_EOL.PHP_EOL;

  27. }


  28. public function onWorkStart($serv, $worker_id) {

  29. echo "#### onWorkStart ####".PHP_EOL.PHP_EOL;

  30. }


  31. public function onRequest($request, $response) {

  32. $response->header("Content-Type", "text/html; charset=utf-8");

  33. $html = "<h1>你好 Swoole.</h1>";

  34. $response->end($html);

  35. }

  36. }


  37. $server = new Server();

二、路由控制

示例效果:

图片

目录结构:

  1. ├─ swoole_http -- 代码根目录

  2. ├─ server.php

  3. ├─ controller

  4. ├── Index.php

  5. ├── Login.php

示例代码:

server.php

  1. <?php


  2. class Server

  3. {

  4. private $serv;


  5. public function __construct() {

  6. $this->serv = new swoole_http_server("0.0.0.0", 9501);

  7. $this->serv->set([

  8. 'worker_num' => 2, //开启2个worker进程

  9. 'max_request' => 4, //每个worker进程 max_request设置为4次

  10. 'document_root' => '',

  11. 'enable_static_handler' => true,

  12. 'daemonize' => false, //守护进程(true/false)

  13. ]);


  14. $this->serv->on('Start', [$this, 'onStart']);

  15. $this->serv->on('WorkerStart', [$this, 'onWorkStart']);

  16. $this->serv->on('ManagerStart', [$this, 'onManagerStart']);

  17. $this->serv->on("Request", [$this, 'onRequest']);


  18. $this->serv->start();

  19. }


  20. public function onStart($serv) {

  21. echo "#### onStart ####".PHP_EOL;

  22. swoole_set_process_name('swoole_process_server_master');


  23. echo "SWOOLE ".SWOOLE_VERSION . " 服务已启动".PHP_EOL;

  24. echo "master_pid: {$serv->master_pid}".PHP_EOL;

  25. echo "manager_pid: {$serv->manager_pid}".PHP_EOL;

  26. echo "########".PHP_EOL.PHP_EOL;

  27. }


  28. public function onManagerStart($serv) {

  29. echo "#### onManagerStart ####".PHP_EOL.PHP_EOL;

  30. swoole_set_process_name('swoole_process_server_manager');

  31. }


  32. public function onWorkStart($serv, $worker_id) {

  33. echo "#### onWorkStart ####".PHP_EOL.PHP_EOL;

  34. swoole_set_process_name('swoole_process_server_worker');


  35. spl_autoload_register(function ($className) {

  36. $classPath = __DIR__ . "/controller/" . $className . ".php";

  37. if (is_file($classPath)) {

  38. require "{$classPath}";

  39. return;

  40. }

  41. });

  42. }


  43. public function onRequest($request, $response) {

  44. $response->header("Server", "SwooleServer");

  45. $response->header("Content-Type", "text/html; charset=utf-8");

  46. $server = $request->server;

  47. $path_info = $server['path_info'];

  48. $request_uri = $server['request_uri'];


  49. if ($path_info == '/favicon.ico' || $request_uri == '/favicon.ico') {

  50. return $response->end();

  51. }


  52. $controller = 'Index';

  53. $method = 'home';



  54. if ($path_info != '/') {

  55. $path_info = explode('/',$path_info);

  56. if (!is_array($path_info)) {

  57. $response->status(404);

  58. $response->end('URL不存在');

  59. }


  60. if ($path_info[1] == 'favicon.ico') {

  61. return;

  62. }


  63. $count_path_info = count($path_info);

  64. if ($count_path_info > 4) {

  65. $response->status(404);

  66. $response->end('URL不存在');

  67. }


  68. $controller = (isset($path_info[1]) && !empty($path_info[1])) ? $path_info[1] : $controller;

  69. $method = (isset($path_info[2]) && !empty($path_info[2])) ? $path_info[2] : $method;

  70. }


  71. $result = "class 不存在";


  72. if (class_exists($controller)) {

  73. $class = new $controller();

  74. $result = "method 不存在";

  75. if (method_exists($controller, $method)) {

  76. $result = $class->$method($request);

  77. }

  78. }


  79. $response->end($result);

  80. }

  81. }


  82. $server = new Server();

Index.php

  1. <?php


  2. class Index

  3. {

  4. public function home($request)

  5. {

  6. $get = isset($request->get) ? $request->get : [];


  7. //@TODO 业务代码


  8. $result = "<h1>你好,Swoole。</h1>";

  9. $result.= "GET参数:".json_encode($get);

  10. return $result;

  11. }

  12. }

Login.php

  1. <?php


  2. class Login

  3. {

  4. public function index($request)

  5. {

  6. $post = isset($request->post) ? $request->post : [];


  7. //@TODO 业务代码


  8. return "<h1>登录成功。</h1>";

  9. }

  10. }

小结

一、Swoole 可以替代 Nginx 吗?

暂时不能,随着 Swoole 越来越强大,以后说不准。

官方建议 Swoole 与 Nginx 结合使用。

Http\Server 对 Http 协议的支持并不完整,建议仅作为应用服务器。并且在前端增加Nginx作为代理。

根据自己的 Nginx 配置文件,可以自行调整。

比如:可以新增一个配置文件

enable-swoole-php.conf

  1. location ~ [^/]\.php(/|$)

  2. {

  3. proxy_http_version 1.1;

  4. proxy_set_header Connection "keep-alive";

  5. proxy_set_header X-Real-IP $remote_addr;

  6. proxy_pass http://127.0.0.1:9501;

  7. }

我们都习惯于将虚拟域名的配置文件放在 vhost 文件夹中。

比如,虚拟域名的配置文件为:local.swoole.com.conf,可以选择加载 enable-php.conf ,也可以选择加载 enable-swoole-php.conf。

配置文件供参考:

  1. server

  2. {

  3. listen 80;

  4. #listen [::]:80;

  5. server_name local.swoole.com ;

  6. index index.html index.htm index.php default.html default.htm default.php;

  7. root /home/wwwroot/project/swoole;


  8. #include rewrite/none.conf;

  9. #error_page 404 /404.html;


  10. #include enable-php.conf;

  11. include enable-swoole-php.conf;


  12. location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$

  13. {

  14. expires 30d;

  15. }


  16. location ~ .*\.(js|css)?$

  17. {

  18. expires 12h;

  19. }


  20. location ~ /.well-known {

  21. allow all;

  22. }


  23. location ~ /\.

  24. {

  25. deny all;

  26. }


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

  28. }

当前,我们直接编辑 server 段的代码也是可以的。

二、修改了 controller 文件夹中的业务代码,每次都是重启服务才生效吗?

不是,每次重启服务可能会影响到正常用户使用的,正常处理的请求会被强制关闭。

在本地运行 路由控制 的代码时,试试这个命令:

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

给 master 进程发送一个 USR1 的信号,当 Swoole Server 接到这个信号后,就会让所有 worker 在处理完当前的请求后,进行重启。

如果查看所有的进程,试试这个命令:

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

需要文章中源码的,关注公众号,回复“swoole http”即可。

扩展

  • 可以试着上传文件,做一个小的FTP服务器。

  • 可以学习 Swoole 开源框架:EasySwoole、Swoft、One。

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

推荐阅读

本文欢迎转发,转发请注明作者和出处,谢谢!

图片

34790Swoole HTTP 的应用

这个人很懒,什么都没留下

文章评论