HTTP 长连接
当客户端发起一个http 请求到服务器,服务器会对这个请求进行相应,发现回客户端。这整个过程是通过建立一个tcp 连接来完成的,任务完成连接中断。
我们现在访问的Web 页面越来越丰富了,页面中包含这大量的Web 资源。如:图像,JS 文件,CS 文件,Flash 文件。每一个WEB 资源都会建立一个HTTP 会话。
我们现在普遍使用的是HTML1.1 协议版本,它其中的一个新特性就是keep-alive( 长连接) 。
使用长连接后,客户端与服务器建立了第一次连接后会一直保持着打开状态。浏览器可以继续通过相同的连接发送请求,不需要再为对每一个WEB 资源的请求分别建立连接,大量节省了每个请求建立新连接所需的时间和带宽。
长连接需要客户端和服务器都支持,现在主流的浏览器都支持,服务器需要配置(如:apache 默认KeepAlive 为On )。
它的原理就是当服务器端返回给服务器的头信息中发送一个Content-Length 头(返回信息正文长度),它将页面的所有信息的长度计算后写入。
但是它也有它的弱点,KeepAlive 在有比较多的静态文件(图片,js 等)比较提高性能,会大量的节约http 的连接数量,在一个请求中完成多个Web 资源的接受。但是如果是动态脚本比如说 是php ,KeepAlive 就没有什么性能提升了。很多的程序需要,确实需要使用KeepAlive ,就需要调高KeepAliveTimeOut 参数,但是这样在大量客户端访问的情况下,会大量堆积httpd 进程,最终导致服务崩溃。
下面是我写的一个测试例子。
不使用 KeepAlive :
ab -n 10000 -c 1 http://localhost/profitMonitor/test.html
……………………………………
Concurrency Level: 1
Time taken for tests: 224.039 seconds
Complete requests: 10000
Failed requests: 0
Write errors: 0
Total transferred: 5440000 bytes
HTML transferred: 2580000 bytes
Requests per second: 44.64 [#/sec] (mean)
Time per request: 22.404 [ms] (mean)
Time per request: 22.404 [ms] (mean, across all concurrent requests)
Transfer rate: 23.71 [Kbytes/sec] received
Connection Times (ms)
min mean[+/-sd] median max
Connect: 0 1 4.1 0 31
Processing: 16 21 7.6 16 63
Waiting: 16 19 6.8 16 63
Total: 16 22 7.9 16 63
Percentage of the requests served within a certain time (ms)
50% 16
66% 31
75% 31
80% 31
90% 31
95% 31
98% 31
99% 31
100% 63 (longest request)
使用 KeepAlive
ab -k -n 10000 -c 1 http://localhost/profitMonitor/test.html
……………………………………
Concurrency Level: 1
Time taken for tests: 130.298 seconds
Complete requests: 10000
Failed requests: 0
Write errors: 0
Keep-Alive requests: 9951
Total transferred: 5812796 bytes
HTML transferred: 2580000 bytes
Requests per second: 76.75 [#/sec] (mean)
Time per request: 13.030 [ms] (mean)
Time per request: 13.030 [ms] (mean, across all concurrent requests)
Transfer rate: 43.57 [Kbytes/sec] received
Connection Times (ms)
min mean[+/-sd] median max
Connect: 0 0 0.5 0 16
Processing: 0 13 9.9 16 297
Waiting: 0 13 9.9 16 297
Total: 0 13 9.9 16 297
Percentage of the requests served within a certain time (ms)
50% 16
66% 16
75% 16
80% 16
90% 16
95% 16
98% 16
99% 31
100% 297 (longest request)