目录
当前位置: 首页 > 文档资料 > Swoole 内核开发 >

Http单连接并发

优质
小牛编辑
136浏览
2023-12-01

Http 协议是目前互联网应用最广泛的网络通信协议,在服务端编程中大量使用 Http+JSON 作为 RPC 服务。实际上 Http 协议有一个缺陷就是无法支持单连接并发,必须是请求应答式的。调用 Http 接口时一般使用 TCP 短连接方式。

Http 1.1版本虽然支持了Keep-Alive,在一定程度上解决了短连接的问题,服务调用方和被调方可以使用Keep-Alive来维持TCP长连接,降低connectclose带来的网络通信开销。

但使用KeepAlive可能会导致服务提供的TCP连接数太多,假设主调方每秒需要产生1000次并发请求,主调方共100台机器,总的QPS10万,那么可能就需要建立10万TCP连接。

那么如何能实现Http协议的单连接并发呢?实际上也有解决的方案。

Http Pipeline

Http 1.1协议中增加了Http Pipeline,可以实现了多个http请求但不需要等待响应就能够写进同一个Socket的技术,普通情况下通过同一个TCP数据包发送多个Http请求,而向网络上发送更少的TCP数据包,大幅减轻网络负载;只有幂等的请求能够被管线化,例如GET请求;而POST请求不应该被管线化。

客户端编写:

<?php
$sock = stream_socket_client("tcp://127.0.0.1:80/");
stream_set_chunk_size($sock, 2*1024*1024);

$data = "GET / HTTP/1.1\r\n";
$data .= "Host: localhost\r\n";
$data .= "Connection: keep-alive\r\n";
$data .= "\r\n";

fwrite($sock, $data);
fwrite($sock, $data);

echo fread($sock,  2*1024*1024);

执行:

htf@LAPTOP-0K15EFQI:~/swoole-src/examples/http$ php pipeline.php
HTTP/1.1 200 OK
Server: nginx/1.14.0 (Ubuntu)
Date: Thu, 10 Oct 2019 14:29:34 GMT
Content-Type: text/html
Content-Length: 612
Last-Modified: Sun, 04 Nov 2018 10:49:43 GMT
Connection: keep-alive
ETag: "5bdecec7-264"
Accept-Ranges: bytes

<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
    body {
        width: 35em;
        margin: 0 auto;
        font-family: Tahoma, Verdana, Arial, sans-serif;
    }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>

<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>

<p><em>Thank you for using nginx.</em></p>
</body>
</html>
HTTP/1.1 200 OK
Server: nginx/1.14.0 (Ubuntu)
Date: Thu, 10 Oct 2019 14:29:34 GMT
Content-Type: text/html
Content-Length: 612
Last-Modified: Sun, 04 Nov 2018 10:49:43 GMT
Connection: keep-alive
ETag: "5bdecec7-264"
Accept-Ranges: bytes

<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
    body {
        width: 35em;
        margin: 0 auto;
        font-family: Tahoma, Verdana, Arial, sans-serif;
    }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>

<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>

<p><em>Thank you for using nginx.</em></p>
</body>
</html>

可以看到在上述程序代码中,同时发送了2Http请求,而Nginx服务器也返回了2Http响应。