Http单连接并发
优质
小牛编辑
136浏览
2023-12-01
Http 协议
是目前互联网应用最广泛的网络通信协议,在服务端编程中大量使用 Http+JSON
作为 RPC 服务。实际上 Http 协议有一个缺陷就是无法支持单连接并发,必须是请求应答式的。调用 Http 接口时一般使用 TCP 短连接方式。
Http 1.1
版本虽然支持了Keep-Alive
,在一定程度上解决了短连接的问题,服务调用方和被调方可以使用Keep-Alive
来维持TCP
长连接,降低connect
和close
带来的网络通信开销。
但使用KeepAlive
可能会导致服务提供的TCP
连接数太多,假设主调方每秒需要产生1000
次并发请求,主调方共100
台机器,总的QPS
为10万
,那么可能就需要建立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>
可以看到在上述程序代码中,同时发送了2
个Http
请求,而Nginx
服务器也返回了2
个Http
响应。