iis服务器助手广告广告
返回顶部
首页 > 资讯 > 精选 >Swoole与HTTP的使用介绍
  • 885
分享到

Swoole与HTTP的使用介绍

2023-06-07 21:06:12 885人浏览 泡泡鱼
摘要

这篇文章主要讲解了“Swoole与Http的使用介绍”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Swoole与HTTP的使用介绍”吧!目标了解swoole的http_server的使用了解

这篇文章主要讲解了“Swoole与Http的使用介绍”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Swoole与HTTP的使用介绍”吧!

Swoole与HTTP的使用介绍

目标

  • 了解swoole的http_server的使用

  • 了解swoole的tcp服务开发

  • 实际项目中问题如粘包处理、代理热更新、用户验证等。

  • swoole与现有框架结合

推荐(免费):swoole

风格

  • 偏基础重代码

环境

  • PHP版本:

  • Swoole版本:https://GitHub.com/swoole/swoole-src

  • zphp开发框架:https://github.com/shenzhe/zphp

HTTP Server

  • 静态文件处理

  • 动态请求与框架结合

# 查看SWOOLE版本$ php -r 'echo SWOOLE_VERSioN;'4.3.1

基础概念

HTTP报文

关于HTTP请求报文的组成结构

Swoole与HTTP的使用介绍

HTTP请求报文结构

POST /search HTTP/1.1  Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msWord, application/x-silverlight, application/x-shockwave-flash, **"  }  ["server"]=>array(10) {    ["request_method"]=>string(3) "GET"    ["request_uri"]=>string(1) "/"    ["path_info"]=>string(1) "/"    ["request_time"]=>int(1561689532)    ["request_time_float"]=>float(1561689533.0563)    ["server_port"]=>int(9501)    ["remote_port"]=>int(51188)    ["remote_addr"]=>string(9) "127.0.0.1"    ["master_time"]=>int(1561689532)    ["server_protocol"]=>string(8) "HTTP/1.1"  }  ["request"]=>NULL  ["cookie"]=>NULL  ["get"]=>NULL  ["files"]=>NULL  ["post"]=>NULL  ["tmpfiles"]=>NULL}
Http\Request->$header

HTTP请求的头部信息,类型为数组,所有的键名均为小写。

$host = $request->header["host"];$accept = $request->header["accept"];

Http\Request->$server

HTTP请求相关的服务器信息,相当于PHP的$_SERVER全局数组,包含了HTTP请求的方法、URL路径、客户端IP等信息。服务器信息为关联数组,数组中的键名全部小写,并且与PHP的$_SERVER数组保持一致。

$request_method = $request->server["request_method"];$request_time = $request->server["request_time"];$request_uri = $request->server["request_uri"];

请求路径

Google的Chrome浏览器访问服务器是会产生两次请求,这是因为Chrome会自动请求一次favicon.ico文件,所以服务器会收到两个HTTP请求,通过打印$request->server["request_uri"]可以查看到请求URL路径。如果需要屏蔽掉对favicon.ico的请求,可采用以下方式。

$uri = $request->server["request_uri"];if($uri == "/favicon.icon"){  $respoonse->status(404);  $response->end();}

收包时间

request_time请求时间是在Worker工作进程中设置的,在SWOOLE_PROCESS多进程模式下存在dispatch分发的过程,因此可能会与实际收包时间存在偏差,尤其当请求量超过服务器处理能力时,有可能滞后于实际收包时间。

可通过Server->getClientInfo()方法获取last_time以获取 准确的收包时间。

//获取客户端文件描述符$fd = $request->fd;if(!empty($fd)){    //获取连接信息    $clientinfo = $server->getClientInfo($fd);    var_dump($clientinfo);    //获取收包时间    var_dump($clientinfo["last_time"]);}

客户端信息

Server->getClientInfo()用于获取连接的客户端信息

bool|array Server->getClientInfo(int $fd, int $extraData, bool $ignoreError = false)
  • int $fd 表示客户端连接文件描述符

  • int $extraData 表示扩展信息是保留参数目前无任何效果

  • bool $ignoreError 表示是否忽略错误,若设置为true表示即使连接关闭也会返回连接信息。

如果传入的$fd客户端连接文件描述符存在则返回一个数组,若不存在或已关闭则返回false

array(10) {  ["server_port"]=>int(9501)  ["server_fd"]=>int(4)  ["Socket_fd"]=>int(12)  ["socket_type"]=>int(1)  ["remote_port"]=>int(51194)  ["remote_ip"]=>string(9) "127.0.0.1"  ["Reactor_id"]=>int(0)  ["connect_time"]=>int(1561690606)  ["last_time"]=>int(1561690606)  ["close_errno"]=>int(0)}

Http\Request->$get

HTTP请求的GET参数,相当于PHP中的$_GET,格式为键值对的关联数组。为防止HASH攻击,GET参数最大不允许超过128个。

$get = $request->get;//获取HTTP请求的所有GET参数

HTTP的GET请求只有一个HTTP Header头,Swowole底层使用固定大小的内存缓冲区为8K,而且不可修改。如果请求不是正确的HTTP请求,将会出现错误,底层会抛出错误。

WARN swReactorThead_onReceive_http_request: http header is too long.

Http\Request->$post

HTTP请求携带POST参数,格式为键值对的关联数组,POSTHeader加起来的尺寸不得超过package_max_length的设置,否则会认为是恶意请求,另外POST参数的个数不得超过128个。

$post = $request->post;

由于POST文件上传时最大尺寸收到package_max_length配置项目的限制,默认为2MB,可以调用swoole_server->set传入新值修改尺寸。

由于Swoole底层是全内存的,因此如果设置过大可能会导致大量并发请求,将服务器资源耗尽。

设置计算方法:最大内存占用 = 最大并发请求数量 * package_max_length

当使用CURL发送POST请求时服务器端会超时

CURL在发送较大的POST请求时会首先发送一个100-continue的请求,当收到服务器的回应才会发送实际的POST数据。然后swoole_http_server并不支持100-continue,因此会导致CURL请求超时。解决的办法时关闭CURL的100-continue。

$ch = curl_init();curl_setopt($ch, CURLOPT_URL, $url);curl_setopt($ch, CURLOPT_HEADER, 0);curl_setopt($ch, CURLOPT_POST, 1);//设置为POST方式curl_setopt($ch, CURLOPT_HTTPHEADER, ["Exception:"]);curl_setopt($ch, CURLOPT_POSTFIELDS, $data);curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

Http\Request->$cookie

HTTP请求携带的COOKIE信息,格式为键值对的关联数组。

Http\Request->$files

HTTP请求携带的文件上传信息,类型为以fORM表单名称为key键名的二维数组,与PHP原生的$_FILES相同,最大文件尺寸不得超过package_max_length中设置的值,不要使用Swoole\Http\Server处理大文件上传。

$files = $request->files;var_dump($files);
array(5) {    [name] => facepalm.jpg    [type] => image/jpeg    [tmp_name] => /tmp/swoole.upfile.n3FmFr    [error] => 0    [size] => 15476}
  • name表示浏览器上传时传入的文件名称

  • type表示浏览器上传时的MIME类型

  • tmp_name 表示浏览器上传的临时文件,文件名默认以/tmp/swoole.upfile开头。

  • size表示上传文件的尺寸

Swoole1.9.10+版本支持is_uploaded_filemove_uploaded_file函数。当HTTP请求对象$request对象销毁时,会自动删除上传的临时文件。

Http\Request->rawContent()

rawContent表示获取原始的POST包体,用于非application/x-www-form-urlencode格式的HTTP的POST请求。等同于原生PHP的fopen("php://input"),有时服务器不需要解析HTTP的POST请求参数。

Swoole1.7.18+版本增加了http_parse_post配置用于关闭或开启POST数据解析。

string HTTP\Request->rawContent();

Http\Request->getData()

getData()方法用于获取完整的HTTP请求报文,包括 Http Header和`HTTP Body消息体。

function swoole_http_request_getData() : string

getData需要Swoole1.10.3或Swoole2.1.2或更高的版本。

响应对象

swoole_http_response响应对象是进程隔离的,不能跨越进程或对象。如果是当前进程中,想使用fd文件描述符保存response响应对象、存储上下文,可使用PHP全局数组变量来保存。

swoole_http_response响应对象,通过调用此对象的方法实现HTTP响应的发送,当响应对象销毁时,如果没有调用end发送HTTP响应,底层会自动执行end方法。不要使用&符号引用$response对象。

object(Swoole\Http\Response)#7 (4) {  ["fd"]=>int(1)  ["header"]=>NULL  ["cookie"]=>NULL  ["trailer"]=>NULL}

HTTP服务器Response响应对象,通过调过此对象的方法,实现HTTP响应发送。当Response对象销毁时,如果未调用则直接调用end方法,不要使用&符号引用$response对象。

Http\Response->header

function Http\Response->header(  string $key,  string $value,  bool $ucworods = true)

header方法用于设置HTTP响应的Header头信息,如果设置失败返回false,设置成功则无返回值。

  • string $key 表示HTTP头的Key

  • string $value 表示HTTP头的Value

  • bool $ucwords 表示是否需要对Key进行HTTP约定格式化,默认true会自动格式化。

$response->header("Content-Type", "image/jpeg", true);

跨域处理

$origin = $request->header['origin'];// Access-Control-Allow-Origin 不能使用 *,这样修改是不支持php版本低于7.0的。// $response->header('Access-Control-Allow-Origin', '*');$response->header('Access-Control-Allow-Origin', $origin);$response->header('Access-Control-Allow-Methods', 'OPTIONS');$response->header('Access-Control-Allow-Headers', 'x-requested-with,session_id,Content-Type,token,Origin');$response->header('Access-Control-Max-Age', '86400');$response->header('Access-Control-Allow-Credentials', 'true');if ($request->server['request_method'] == 'OPTIONS') {  $response->status(200);  $response->end();  return;};

Http\Response->cookie

cookie方法用来设置HTTP响应的Cookie信息,方法参数与原生PHP的setcookie函数完全一致。

function  Http\Response->cookie(  string $key,  string $value = "",   int $expire = 0,  string $path = "/",  string $domain = "",  bool  $secure = false,  bool $httponly = false)

Cookie设置必须在end方法之前方才生效,Swoole底层自动会对$value进行urlencode编码处理,同时允许设置多个相同的$key的Cookie。

Http\Response->status

swoole_http_response->status(  int $http_status_code)

status方法用于发送HTTP状态码,$http_status_code必须是合法的HTTP状态码,如2xx、3xx、4xx、5xx等,若不是在会报错,另外status方法也必须在$response->end()之前执行方才生效。

  • string $url表示跳转的新地址会作为HTTP Header头中的Location选项进行发送

  • int $http_code 表示状态码,默认为302临时跳转,传入301表示永久跳转。

Http\Response->redirect

redirect方法适用于Swoole2.2.0+版本,用于发送HTTP跳转,调用后会自动执行end方法并发送结束响应。

function Http\Response->redirect(  string $url,  int $http_code = 302)

例如

$server = new swoole_http_server("0.0.0.0", 9501, SWOOLE_BASE);$server->on("request", function(swoole_http_request $request, swoole_http_response $response){  $url = "http://www.baidu.com";  $response->redirect($url, 301);});$server->start();

Http\Response->write

write方法用于启用HTTP的chunk分段以向浏览器发送相应的内容,使用write分段发送数据后end方法将不再接收任何参数,调用end方法后会发送一个长度为0的分段chunk表示数据传输完毕。

bool Http\Response->write(string $data)

参数$data表示要发送的数据内容,最大长度不得超过2MB,受buffer_output_size配置项控制。

Http\Response->sendfile

sendfile用于发送文件到浏览器

function Http\Response->sendfile(  string $filename,  int $offset = 0,  int $length = 0)
  • string $filename 表示要发送的文件名称,文件不存在或没有访问权限则会发送失败。

  • int $offset 表示上传文件的偏移量,可以指定从文件在中间部分开始传输数据,用于断点续传,适用于Swoole1.9.11+。

  • int $length 表示发送数据的尺寸,默认为整个文件的尺寸,适用于Swoole1.9.11+。

$response->header("Content-Type", "image/jpeg");$filepath = $request->server["request_uri"];$filename = __DIR__.$filepath;$response->sendfile($filename);

由于Swoole底层无法推断要发送文件的媒体类型MIME格式,因此需要应用程序指定Content-Type。调用sendfile前不得使用write方法发送HTTP数据段Chunk,调用sendfile后Swoole底层会自动执行end方法,另外sendfile不支持gzip压缩。

Http\Response->end

end方法用于发送HTTP响应体,并结束请求处理。

function Http\Response->end(string $html);

end方法只能调用一次,如果需要分多次向客户端发送数据下需使用write方法,send操作后将会向客户端浏览器发送HTML内容。如果客户端开启了KeepAlive连接会保持,服务器会等待下一次请求。如果没有开启KeepAlive服务器将会切断连接。

Http\Response->detach

detach表示分离响应对应,调用后$response对象销毁时将不会自动执行end方法,一般detach会与Http\Response::create以及Server::send配合使用,适用于Swoole2.2.0+版本。

function Http\Response->detach():bool

detach方法操作后,若客户端已经完成响应则会返回true,否则返回false

detach应用于跨进程响应

在某些情况下需要在Task任务进程中对客户端发出响应,此时可以利用detach方法使$response对象独立,如此一来在Task任务进程中就可以重新构建$response对象以发起HTTP请求响应。

<?php//创建HTTP服务器对象$host = "0.0.0.0";$port = 9501;$server = new swoole_http_server($host, $port);//设置服务器运行参数$configs = [];$configs["worker_num"] = 1;//设置Worker工作进程数量$configs["task_worker_num"]  = 1;//设置Task任务进程数量$configs["daemonize"] = 0;//设置是否已后台守护进程运行$server->set($configs);//注册客户端请求处理回调函数$server->on("request", function(swoole_http_request $request, swoole_http_response $response) use($server){    //分离响应对象    $response->detach();    //在Task任务进程中对客户端发出响应    $fd = strval($response->fd);    $server->task($fd);});//注册异步任务处理回调函数$server->on("task", function(swoole_http_server $server, $worker_id, $data){    //创建响应对象    $response = swoole_http_response::create($data);    //向客户端发送响应    $html = "in task";    $response->end($html);});//注册Task异步任务执行完毕回调函数$server->on("finish", function(){    echo "[finish] task".PHP_EOL;});//启动服务器$server->start();

detach方法应用于发送任意内容

在某些特殊场景下,需要对客户端发送特殊的响应内容,Http\Response对象自带的end方法无法满足需求,可以使用detach方法分离响应对象,然后自行组包并使用Server::send方法发送数据。

<?php//创建HTTP服务器对象$host = "0.0.0.0";$port = 9501;$server = new swoole_http_server($host, $port);//设置服务器运行参数$configs = [];$configs["worker_num"] = 2;//设置Worker工作进程数量$configs["daemonize"] = 0;//设置是否已后台守护进程运行$server->set($configs);//注册监听客户端HTTP请求回调事件$server->on("request", function(swoole_http_request $request, swoole_http_response $response) use($server){    //分离响应对象    $response->detach();    //自行组包并使用Server::send方法发送数据    $fd = $response->fd;    $message = "HTTP/1.1 200 OK\r\n";    $message .= "Server: server\r\n";    $message .= "\r\n";    $message .= "Hello World\n";    $server->send($fd, $message);});//启动服务器$server->start();

Http\Response::create

create静态方法用于构造新的Http\Response响应对象,使用前必须调用detach方法将旧有$response对象分离,否则 可能会造成同一个请求发送两次响应内容。

function Http\Response::createE(int $fd) : Http\Response

create静态方法的参数$fd表示需要绑定连接的文件描述符,调用Http\Response对象的end方法和write方法时会向此连接发送数据。如果调用成功则返回一个新的Http\Response对象,否则失败返回false,适用于Swoole2.2.0+版本。


注册事件回调函数

Http\Server注册事件回调函数于Http\Server->on相同,不同之处在于HTTP\Server->on不接受onConnectonReceive回调设置,Http\Server->on会额外接受一种新的事务类型onRequest

onRequest 事件

onRequest事件适用于Swoole1.7.7+版本,当服务器收到一个完整的HTTP请求后会调用onRequest函数。

$server->on("request", function(swoole_http_request $request, swoole_http_response $response) use($server){  $html = "success";  $response->end($html);});

onRequest回调函数共有两个参数

  • swoole_http_requst $request HTTP请求信息对象,包含了Header/GET/POST/Cookie等信息。

  • swoole_http_response $response HTTP响应信息对象,支持Cookie/Header/Status等HTTP操作。

onRequest回调函数返回时会销毁$request$response对象,如果未执行$response->end()操作,Swoole底层会自动执行一次$response->end("")

$request$response对象在传递给其它函数时,是不需要添加&取地址的引用符号的,传递后引用计数会增加,当onRequest退出时并不会被销毁。

案例

$ vim http_server.php
<?php$addr = "0.0.0.0";$port = 9501;$svr = new swoole_http_server($addr, $port);$svr->on("request", function(swoole_http_request $rq, swoole_http_response $rp){    //处理动态请求    $path_info = $rq->server["path_info"];    $file = __DIR__.$path_info;    echo "\nfile:{$file}";    if(is_file($file) && file_exists($file)){        $ext = pathinfo($path_info, PATHINFO_EXTENSION);        echo "\next:{$ext}";        if($ext == "php"){            ob_start();            include($file);            $contents = ob_get_contents();            ob_end_clean();        }else{            $contents = file_get_contents($file);        }        echo "\ncontents:{$contents}";        $rp->end($contents);    }else{        $rp->status(404);        $rp->end("404 not found");    }});$svr->start();
# 创建静态文件$ vim index.htmlindex.html# 测试静态文件$ curl 127.0.0.1:9501/index.html# 观察http_server输出file:/home/jc/projects/swoole/chat/index.htmlext:htmlcontents:index.html# 测试动态文件$ vim index.php<?phpecho "index.php";#观察http_server日志输出file:/home/jc/projects/swoole/chat/index.phpext:phpcontents:index.php

获取动态请求的参数

$ vim http_server.php
<?php$addr = "0.0.0.0";$port = 9501;$svr = new swoole_http_server($addr, $port);$svr->on("request", function(swoole_http_request $rq, swoole_http_response $rp){    //获取请求参数    $params = $rq->get;    echo "\nparams:".JSON_encode($params);    //处理动态请求    $path_info = $rq->server["path_info"];    $file = __DIR__.$path_info;    echo "\nfile:{$file}";    if(is_file($file) && file_exists($file)){        $ext = pathinfo($path_info, PATHINFO_EXTENSION);        echo "\next:{$ext}";        if($ext == "php"){            ob_start();            include($file);            $contents = ob_get_contents();            ob_end_clean();        }else{            $contents = file_get_contents($file);        }        echo "\ncontents:{$contents}";        $rp->end($contents);    }else{        $rp->status(404);        $rp->end("404 not found");    }});$svr->start();

测试带参数的请求

$ curl 127.0.0.1:9501?k=v

观察请求参数的输出

params:{"k":"v"}file:/home/jc/projects/swoole/chat/index.htmlext:htmlcontents:index.html

静态文件处理

$ vim mimes.php
<?phpreturn [    "jpg"=>"image/jpeg",    "jpeg"=>"image/jpeg",    "bmp"=>"image/bmp",    "ico"=>"image/x-icon",    "gif"=>"image/gif",    "png"=>"image/png",    "CSS"=>"text/css",    "html"=>"text/html",    "xml"=>"text/xml",    "bin"=>"application/octet-stream",    "js"=>"application/javascript",    "tar"=>"application/x-tar",    "ppt"=>"application/vnd.ms-powerpoint",    "pdf"=>"application/pdf",    "swf"=>"application/x-shockwave-flash",    "zip"=>"application/x-zip-compressed"];
$ vim http_server.php
<?php//创建HTTP服务器$addr = "0.0.0.0";$port = 9501;$srv = new swoole_http_server($addr, $port);//设置HTTP服务器参数$cfg = [];$cfg["worker_num"] = 4;//设置工作进程数量$cfg["daemonize"] = 0;//守护进程化,程序转入后台。$srv->set($cfg);//处理请求$srv->on("request", function(swoole_http_request $rq, swoole_http_response $rp) use($srv){    //获取请求文件信息与文件后缀    $path_info = $rq->server["path_info"];    $ext = pathinfo($path_info, PATHINFO_EXTENSION);    //文件是否存在    $file = __DIR__.$path_info;    if(!is_file($file) || !file_exists($file)){        $rp->status(404);        $rp->end("404 NOT FOUND");    }    //处理静态请求    if($ext != "php"){        //设置响应头信息的内容内容        $mimes = include("mimes.php");        $rp->header("Content-Type", $mimes[$ext]);        //获取静态文件内容        $contents = file_get_contents($file);        //返回内容        $rp->end($contents);    }});//启动服务$srv->start();

发送请求,浏览器访问127.0.0.1:9501/test.jpeg,查看图片。

面向对象

$ vim http_server.php
<?phpclass HttpServer{    public static function run($host, $port, $options=[])    {        $srv = new swoole_http_server($host, $port);        if(!empty($options)){            $srv->set($options);        }        $srv->on("request", function(swoole_http_request $rq, swoole_http_response $rp) use($srv){            $rp->end("test");            $srv->close($rq->fd);        });        $srv->start();    }}HttpServer::run("127.0.0.1", 9501, ["worker_num"=>2, "daemonize"=>0]);

压力测试

使用Apache Bench工具进行压力测试可以发现,swoole_http_server远超过PHP-FPM、golang自带的HTTP服务器、node.js自带的HTTP服务器,性能接近Nginx的静态文件处理。

Swoole的http server与PHP-FPM的性能对比

安装Apache的压测工作ab

$ sudo apt install apache2-util

使用100个客户端跑1000次,平均每个客户端10个请求。

$ ab -c 100 -n 1000 127.0.0.1:9501/index.phpConcurrency Level:      100Time taken for tests:   0.480 secondsComplete requests:      1000Failed requests:        0Total transferred:      156000 bytesHTML transferred:       9000 bytesRequests per second:    2084.98 [#/sec] (mean)Time per request:       47.962 [ms] (mean)Time per request:       0.480 [ms] (mean, across all concurrent requests)Transfer rate:          317.63 [Kbytes/sec] receivedConnection Times (ms)              min  mean[+/-sd] median   maxConnect:        0    1   3.0      0      12Processing:     4   44  10.0     45      57Waiting:        4   44  10.1     45      57Total:         16   45   7.8     45      57Percentage of the requests served within a certain time (ms)  50%     45  66%     49  75%     51  80%     52  90%     54  95%     55  98%     55  99%     56 100%     57 (longest request)

观察可以发现QPS可以达到 Requests per second: 2084.98 [#/sec] (mean)

HTTP SERVER 配置选项

swoole_server::set()用于设置swoole_server运行时的各项参数化。

$cfg = [];// 处理请求的进程数量$cfg["worker_num"] = 4;// 守护进程化$cfg["daemonize"] = 1;// 设置工作进程的最大任务数量$cfg["max_request"] = 0;$cfg["backlog"] = 128;$cfg["max_request"] = 50;$cfg["dispatch_mode"] = 1;$srv->set($cfg);

配置HTTP SERVER参数后测试并发

$ vim http_server.php
<?php//创建HTTP服务器$addr = "0.0.0.0";$port = 9501;$srv = new swoole_http_server($addr, $port);//设置HTTP服务器参数$cfg = [];$cfg["worker_num"] = 4;//设置工作进程数量$cfg["daemonize"] = 1;//守护进程化,程序转入后台。$srv->set($cfg);$srv->on("request", function(swoole_http_request $rq, swoole_http_response $rp){    //获取请求参数    $params = $rq->get;    echo "\nparams:".json_encode($params);    //处理动态请求    $path_info = $rq->server["path_info"];    $file = __DIR__.$path_info;    echo "\nfile:{$file}";    if(is_file($file) && file_exists($file)){        $ext = pathinfo($path_info, PATHINFO_EXTENSION);        echo "\next:{$ext}";        if($ext == "php"){            ob_start();            include($file);            $contents = ob_get_contents();            ob_end_clean();        }else{            $contents = file_get_contents($file);        }        echo "\ncontents:{$contents}";        $rp->end($contents);    }else{        $rp->status(404);        $rp->end("404 not found");    }});//启动服务$srv->start();

查看进程

$ ps -ef|grep http_server.phproot     16224  1207  0 22:41 ?        00:00:00 php http_server.phproot     16225 16224  0 22:41 ?        00:00:00 php http_server.phproot     16227 16225  0 22:41 ?        00:00:00 php http_server.phproot     16228 16225  0 22:41 ?        00:00:00 php http_server.phproot     16229 16225  0 22:41 ?        00:00:00 php http_server.phproot     16230 16225  0 22:41 ?        00:00:00 php http_server.phproot     16233  2456  0 22:42 pts/0    00:00:00 grep --color=auto http_server.php

查看后台守护进程

$ ps axuf|grep http_server.phproot     16622  0.0  0.0  21536  1044 pts/0    S+   22:46   0:00  |   |           \_ grep --color=auto http_server.phproot     16224  0.0  0.3 269036  8104 ?        Ssl  22:41   0:00  \_ php http_server.phproot     16225  0.0  0.3 196756  8440 ?        S    22:41   0:00      \_ php http_server.phproot     16227  0.0  0.6 195212 14524 ?        S    22:41   0:00          \_ php http_server.phproot     16228  0.0  0.6 195212 14524 ?        S    22:41   0:00          \_ php http_server.phproot     16229  0.0  0.6 195212 14524 ?        S    22:41   0:00          \_ php http_server.phproot     16230  0.0  0.6 195212 14524 ?        S    22:41   0:00          \_ php http_server.php$ ps auxf|grep http_server.php|wc -l7

杀死后台进程

# 强杀后台进程$ kill -9 $(ps aux|grep swoole|grep -v grep|awk '{print $2}')$ kill -9 16224$ kill -9 16225$ kill -9 16227$ kill -9 16228$ kill -9 16229$ kill -9 16230# 重启后台进程$ kill -10 $(ps aux|grep http_server|grep -v grep|awk '{print $2}')

压测

$ ab -c 100 -n 1000 127.0.0.1:9501/index.phpServer Software:        swoole-http-serverServer Hostname:        127.0.0.1Server Port:            9501Document Path:          /index.phpDocument Length:        9 bytesConcurrency Level:      100Time taken for tests:   0.226 secondsComplete requests:      1000Failed requests:        0Total transferred:      156000 bytesHTML transferred:       9000 bytesRequests per second:    4417.72 [#/sec] (mean)Time per request:       22.636 [ms] (mean)Time per request:       0.226 [ms] (mean, across all concurrent requests)Transfer rate:          673.01 [Kbytes/sec] receivedConnection Times (ms)              min  mean[+/-sd] median   maxConnect:        0    1   2.8      0      11Processing:     4   21   7.2     20      49Waiting:        1   21   7.2     20      49Total:          5   22   7.6     20      56Percentage of the requests served within a certain time (ms)  50%     20  66%     23  75%     25  80%     26  90%     30  95%     38  98%     45  99%     53 100%     56 (longest request)

观察可以发现QPC为Requests per second: 4417.72 [#/sec] (mean)

性能优化

使用swoole_http_server服务后,若发现服务的请求耗时监控毛刺十分严重,接口耗时波动较大的情况,可以观察下服务的响应包response的大小,若响应包超过1~2M甚至更大,则可判断是由于包太多而且很大导致服务响应波动较大。

为什么响应包惠导致相应的时间波动呢?主要有两个方面的影响,第一是响应包太大导致Swoole之间进程通信更加耗时并占用更多资源。第二是响应包太大导致Swoole的Reactor线程发包更加耗时。

感谢各位的阅读,以上就是“Swoole与HTTP的使用介绍”的内容了,经过本文的学习后,相信大家对Swoole与HTTP的使用介绍这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是编程网,小编将为大家推送更多相关知识点的文章,欢迎关注!

--结束END--

本文标题: Swoole与HTTP的使用介绍

本文链接: https://www.lsjlt.com/news/250256.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • C++ 生态系统中流行库和框架的贡献指南
    作为 c++++ 开发人员,通过遵循以下步骤即可为流行库和框架做出贡献:选择一个项目并熟悉其代码库。在 issue 跟踪器中寻找适合初学者的问题。创建一个新分支,实现修复并添加测试。提交...
    99+
    2024-05-15
    框架 c++ 流行库 git
  • C++ 生态系统中流行库和框架的社区支持情况
    c++++生态系统中流行库和框架的社区支持情况:boost:活跃的社区提供广泛的文档、教程和讨论区,确保持续的维护和更新。qt:庞大的社区提供丰富的文档、示例和论坛,积极参与开发和维护。...
    99+
    2024-05-15
    生态系统 社区支持 c++ overflow 标准库
  • c++中if elseif使用规则
    c++ 中 if-else if 语句的使用规则为:语法:if (条件1) { // 执行代码块 1} else if (条件 2) { // 执行代码块 2}// ...else ...
    99+
    2024-05-15
    c++
  • c++中的继承怎么写
    继承是一种允许类从现有类派生并访问其成员的强大机制。在 c++ 中,继承类型包括:单继承:一个子类从一个基类继承。多继承:一个子类从多个基类继承。层次继承:多个子类从同一个基类继承。多层...
    99+
    2024-05-15
    c++
  • c++中如何使用类和对象掌握目标
    在 c++ 中创建类和对象:使用 class 关键字定义类,包含数据成员和方法。使用对象名称和类名称创建对象。访问权限包括:公有、受保护和私有。数据成员是类的变量,每个对象拥有自己的副本...
    99+
    2024-05-15
    c++
  • c++中优先级是什么意思
    c++ 中的优先级规则:优先级高的操作符先执行,相同优先级的从左到右执行,括号可改变执行顺序。操作符优先级表包含从最高到最低的优先级列表,其中赋值运算符具有最低优先级。通过了解优先级,可...
    99+
    2024-05-15
    c++
  • c++中a+是什么意思
    c++ 中的 a+ 运算符表示自增运算符,用于将变量递增 1 并将结果存储在同一变量中。语法为 a++,用法包括循环和计数器。它可与后置递增运算符 ++a 交换使用,后者在表达式求值后递...
    99+
    2024-05-15
    c++
  • c++中a.b什么意思
    c++kquote>“a.b”表示对象“a”的成员“b”,用于访问对象成员,可用“对象名.成员名”的语法。它还可以用于访问嵌套成员,如“对象名.嵌套成员名.成员名”的语法。 c++...
    99+
    2024-05-15
    c++
  • C++ 并发编程库的优缺点
    c++++ 提供了多种并发编程库,满足不同场景下的需求。线程库 (std::thread) 易于使用但开销大;异步库 (std::async) 可异步执行任务,但 api 复杂;协程库 ...
    99+
    2024-05-15
    c++ 并发编程
  • 如何在 Golang 中备份数据库?
    在 golang 中备份数据库对于保护数据至关重要。可以使用标准库中的 database/sql 包,或第三方包如 github.com/go-sql-driver/mysql。具体步骤...
    99+
    2024-05-15
    golang 数据库备份 mysql git 标准库
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作