nginx 伺服器是否要關閉keep-alive

pythontab發表於2014-05-29

最近nginx不知道什麼原因導致經常併發高達4萬。後來朋友說因為keep-alive問題。

特意研究一下keep-alive是什麼。

nginx不像apache,直接有指令keep-alive off/on;它使用的是keepalive_timeout [time],預設的時長為75,可以在http、server、location使用此指令。

nginx keep-alive詳情參考

http://wiki.nginx.org/HttpCoreModule#keepalive_timeout

keepalive_timeout

什麼是Keep-Alive模式?

我們知道HTTP協議採用“請求-應答”模式,當使用普通模式,即非KeepAlive模式時,每個請求/應答客戶和伺服器都要新建一個連線,完成 之後立即斷開連線(HTTP協議為無連線的協議);當使用Keep-Alive模式(又稱持久連線、連線重用)時,Keep-Alive功能使客戶端到服 務器端的連線持續有效,當出現對伺服器的後繼請求時,Keep-Alive功能避免了建立或者重新建立連線。

http 1.0中預設是關閉的,需要在http頭加入”Connection: Keep-Alive”,才能啟用Keep-Alive;http 1.1中預設啟用Keep-Alive,如果加入”Connection: close “,才關閉。目前大部分瀏覽器都是用http1.1協議,也就是說預設都會發起Keep-Alive的連線請求了,所以是否能完成一個完整的Keep- Alive連線就看伺服器設定情況。

從上面的分析來看,啟用Keep-Alive模式肯定更高效,效能更高。因為避免了建立/釋放連線的開銷。下面是RFC 2616 上的總結:

http://tools.ietf.org/html/rfc2616

By opening and closing fewer TCP connections, CPU time is saved in routers and hosts (clients, servers, proxies, gateways, tunnels, or caches), and memory used for TCP protocol control blocks can be saved in hosts.

HTTP requests and responses can be pipelined on a connection. Pipelining allows a client to make multiple requests without waiting for each response, allowing a single TCP connection to be used much more efficiently, with much lower elapsed time.

Network congestion is reduced by reducing the number of packets caused by TCP opens, and by allowing TCP sufficient time to determine the congestion state of the network.

Latency on subsequent requests is reduced since there is no time spent in TCP’s connection opening handshake.

HTTP can evolve more gracefully, since errors can be reported without the penalty of closing the TCP connection. Clients using future versions of HTTP might optimistically try a new feature, but if communicating with an older server, retry with old semantics after an error is reported.

RFC 2616 (P47)還指出:單使用者客戶端與任何伺服器或代理之間的連線數不應該超過2個。一個代理與其它伺服器或程式碼之間應該使用超過2 * N的活躍併發連線。這是為了提高HTTP響應時間,避免擁塞(冗餘的連線並不能程式碼執行效能的提升)。

結論:keep-alive應該開著,以提高速度,特別是一個使用者會在你網站看很多頁面或者你的頁面有很多js,圖片,等等。

如果你的網站是高併發的,但是使用者很多的,一個使用者可能只訪問你一個介面檔案。那麼 close比較好。

最後發現不是keep-alive的事情,我設定了10秒。其他原因導致。


相關文章