您好,登錄后才能下訂單哦!
這里的設置,我們都以HTTP1.1協議為例子。
在首部字段中設置Connection:close
,則在一次請求/響應之后,就會關閉連接。
在首部字段中設置Connection:keep-alive
和Keep-Alive: timeout=60
,表明連接建立之后,空閑時間超過60秒之后,就會失效。如果在空閑第58秒時,再次使用此連接,則連接仍然有效,使用完之后,重新計數,空閑60秒之后過期。
在首部字段中只設置Connection:keep-alive
,表明連接永久有效。
了解怎么設置之后,就開始用起來。然而,問題來了。在請求頭中設置Connection:keep-alive
,為什么連接空閑一段時間之后,還是斷開了呢?這是因為connection字段只有服務端設置才有效。
HTTP操作是請求/響應成對出現的,即先有客戶端發出請求,后有服務端處理請求。所以,一次HTTP操作的終點操作在服務端上,關閉也是由服務端發起的。
接下來我們做做測試,以及show code。下面的測試都是使用Spring RestTemplate,封裝apache http client進行的。為方便講解代碼,先說明長連接的情況,最后再對其他形式做測試總結。
如下,為請求日志。客戶端設置Connection: Keep-Alive
和Keep-Alive: timeout=60
, 服務端設置Connection: Keep-Alive
和Keep-Alive: timeout=5
。
## 客戶端設置有效期為60s[2017-04-26 14:08:00 DEBUG] (org.apache.http.wire:?) - http-outgoing-0 >> "POST /adx-api/api/creative/upload HTTP/1.1[\r][\n]" [2017-04-26 14:08:00 DEBUG] (org.apache.http.wire:?) - http-outgoing-0 >> "Accept: application/json, application/*+json, text/html, application/json, text/javascript[\r][\n]" [2017-04-26 14:08:00 DEBUG] (org.apache.http.wire:?) - http-outgoing-0 >> "Content-Type: application/json;charset=UTF-8[\r][\n]" [2017-04-26 14:08:00 DEBUG] (org.apache.http.wire:?) - http-outgoing-0 >> "User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.16 Safari/537.36[\r][\n]" [2017-04-26 14:08:00 DEBUG] (org.apache.http.wire:?) - http-outgoing-0 >> "Accept-Encoding: gzip,deflate[\r][\n]" [2017-04-26 14:08:00 DEBUG] (org.apache.http.wire:?) - http-outgoing-0 >> "Accept-Language: zh-CN[\r][\n]" [2017-04-26 14:08:00 DEBUG] (org.apache.http.wire:?) - http-outgoing-0 >> "Connection: keep-alive[\r][\n]" [2017-04-26 14:08:00 DEBUG] (org.apache.http.wire:?) - http-outgoing-0 >> "Keep-Alive: timeout=60[\r][\n]" [2017-04-26 14:08:00 DEBUG] (org.apache.http.wire:?) - http-outgoing-0 >> "Content-Length: 396[\r][\n]" [2017-04-26 14:08:00 DEBUG] (org.apache.http.wire:?) - http-outgoing-0 >> "Host: bizdomain[\r][\n]" [2017-04-26 14:08:00 DEBUG] (org.apache.http.wire:?) - http-outgoing-0 >> "[\r][\n]" [2017-04-26 14:08:00 DEBUG] (org.apache.http.wire:?) - http-outgoing-0 >> "request data"##服務端設置有效期為5s[2017-04-26 14:08:00 DEBUG] (org.apache.http.wire:?) - http-outgoing-0 << "HTTP/1.1 200 OK[\r][\n]" [2017-04-26 14:08:00 DEBUG] (org.apache.http.wire:?) - http-outgoing-0 << "Date: Wed, 26 Apr 2017 06:07:58 GMT[\r][\n]" [2017-04-26 14:08:00 DEBUG] (org.apache.http.wire:?) - http-outgoing-0 << "Server: Apache-Coyote/1.1[\r][\n]" [2017-04-26 14:08:00 DEBUG] (org.apache.http.wire:?) - http-outgoing-0 << "Content-Type: text/html;charset=utf-8[\r][\n]"[2017-04-26 14:08:00 DEBUG] (org.apache.http.wire:?) - http-outgoing-0 << "Keep-Alive: timeout=5, max=100[\r][\n]"[2017-04-26 14:08:00 DEBUG] (org.apache.http.wire:?) - http-outgoing-0 << "Connection: Keep-Alive[\r][\n]" [2017-04-26 14:08:00 DEBUG] (org.apache.http.wire:?) - http-outgoing-0 << "Transfer-Encoding: chunked[\r][\n]" [2017-04-26 14:08:00 DEBUG] (org.apache.http.wire:?) - http-outgoing-0 << "[\r][\n]" [2017-04-26 14:08:00 DEBUG] (org.apache.http.wire:?) - http-outgoing-0 << "63[\r][\n]" [2017-04-26 14:08:00 DEBUG] (org.apache.http.wire:?) - http-outgoing-0 << "response data"
客戶端設置的有效期大于服務端的,那么實際連接的有效期呢?三分鐘之后再次請求,從連接池中lease連接的時候,提示Connection expired @ Wed Apr 26 14:08:05
,即在上一次請求之后的5s失效,說明是服務端的設置生效了。
[2017-04-26 14:11:00 DEBUG] (org.apache.http.impl.conn.PoolingHttpClientConnectionManager:?) - Connection request: [route: {}->http://bizdomain:80][total kept alive: 1; route allocated: 1 of 32; total allocated: 1 of 200] [2017-04-26 14:11:00 DEBUG] (org.apache.http.impl.conn.CPool:?) - Connection [id:2][route:{}->http://bizdomain:80][state:null] expired @ Wed Apr 26 14:08:05 GMT+08:00 2017
通過源代碼了解一下連接失效時間的設置過程。
//org.apache.http.impl.execchain.MainClientExec#execute......//從連接池中lease connectionfinal HttpClientConnectionmanagedConn = connRequest.get(timeout > 0 ? timeout : 0, TimeUnit.MILLISECONDS); ......//將conenction封裝在ConnectionHolder中final ConnectionHolder connHolder = new ConnectionHolder(this.log, this.connManager, managedConn); ......// The connection is in or can be brought to a re-usable state.//如果返回值消息頭中connection設置為close,則返回falseif (reuseStrategy.keepAlive(response, context)) { // Set the idle duration of this connection //取出response消息頭中,keep-alive的timeout值 final long duration = keepAliveStrategy.getKeepAliveDuration(response, context); if (this.log.isDebugEnabled()) { final String s; if (duration > 0) { s = "for " + duration + " " + TimeUnit.MILLISECONDS; } else { s = "indefinitely"; } this.log.debug("Connection can be kept alive " + s); } //設置失效時間 connHolder.setValidFor(duration, TimeUnit.MILLISECONDS); connHolder.markReusable(); } else { connHolder.markNonReusable(); }
待讀取響應之后,釋放連接,即:connHolder.releaseConnection()
。調用org.apache.http.impl.conn.PoolingHttpClientConnectionManager#releaseConnection方法。
@Override public void releaseConnection(final HttpClientConnection managedConn, final Object state,final long keepalive, final TimeUnit tunit) { Args.notNull(managedConn, "Managed connection"); synchronized (managedConn) { final CPoolEntry entry = CPoolProxy.detach(managedConn); if (entry == null) { return; } final ManagedHttpClientConnection conn = entry.getConnection(); try { if (conn.isOpen()) { final TimeUnit effectiveUnit = tunit != null ? tunit : TimeUnit.MILLISECONDS; entry.setState(state); //設置失效時間 entry.updateExpiry(keepalive, effectiveUnit); } } finally { 。。。。。。 } } } }
然后再下一次HTTP操作,從連接池中獲取連接時
//org.apache.http.impl.conn.PoolingHttpClientConnectionManager#requestConnection調用org.apache.http.pool.AbstractConnPool#lease,//調用getPoolEntryBlocking,調用org.apache.http.impl.conn.CPoolEntry#isExpired@Overridepublic boolean isExpired(final long now) { final boolean expired = super.isExpired(now); if (expired && this.log.isDebugEnabled()) { //日志中看到的內容 this.log.debug("Connection " + this + " expired @ " + new Date(getExpiry())); } return expired; }
綜上,連接的實際有效時間,是根據response的設置來決定的。
客戶端設置Connection: Close
##connection:close請求,kept alive的連接為0[2017-04-26 13:57:00 DEBUG] (org.apache.http.impl.conn.PoolingHttpClientConnectionManager:?) - Connection request: [route: {}->http://bizdomain:80][total kept alive: 0; route allocated: 0 of 32; total allocated: 0 of 200] [2017-04-26 13:57:00 DEBUG] (org.apache.http.impl.conn.PoolingHttpClientConnectionManager:?) - Connection leased: [id: 0][route: {}->http://bizdomain:80][total kept alive: 0; route allocated: 1 of 32; total allocated: 1 of 200] [2017-04-26 13:57:00 DEBUG] (org.apache.http.impl.execchain.MainClientExec:?) - Opening connection {}->http://bizdomain:80 [2017-04-26 13:57:00 DEBUG] (org.apache.http.impl.conn.DefaultHttpClientConnectionOperator:?) - Connecting to bizdomain/127.0.0.195:80## 建立新連接[2017-04-26 13:57:00 DEBUG] (org.apache.http.impl.conn.DefaultHttpClientConnectionOperator:?) - Connection established 127.0.0.191:49239<->127.0.0.195:80## 客戶端設置短連接[2017-04-26 13:57:00 DEBUG] (org.apache.http.wire:?) - http-outgoing-0 >> "Connection: Close[\r][\n]"## 服務端返回的也是短連接[2017-04-26 13:57:00 DEBUG] (org.apache.http.wire:?) - http-outgoing-0 << "Connection: close[\r][\n]" ##請求完之后,關閉連接 [2017-04-26 13:57:00 DEBUG] (org.apache.http.impl.conn.DefaultManagedHttpClientConnection:?) - http-outgoing-0: Close connection[2017-04-26 13:57:00 DEBUG] (org.apache.http.impl.execchain.MainClientExec:?) - Connection discarded[2017-04-26 13:57:00 DEBUG] (org.apache.http.impl.conn.PoolingHttpClientConnectionManager:?) - Connection released: [id: 0][route: {}->http://bizdomain:80][total kept alive: 0; route allocated: 0 of 32; total allocated: 0 of 200]
如上,當服務端返回Connection: Close
時,客戶端接收完響應,便會關閉連接。
客戶端設置60s超時,服務端設置5s超時
##Keep-Alive: timeout=60 第一次請求,與connection:close無差別[2017-04-26 10:57:00 DEBUG] (org.apache.http.impl.conn.PoolingHttpClientConnectionManager:?) - Connection request: [route: {}->http://bizdomain:80][total kept alive: 0; route allocated: 0 of 32; total allocated: 0 of 200] [2017-04-26 10:57:00 DEBUG] (org.apache.http.impl.conn.PoolingHttpClientConnectionManager:?) - Connection leased: [id: 0][route: {}->http://bizdomain:80][total kept alive: 0; route allocated: 1 of 32; total allocated: 1 of 200] [2017-04-26 10:57:00 DEBUG] (org.apache.http.impl.execchain.MainClientExec:?) - Opening connection {}->http://bizdomain:80## 客戶端設置超時時間60s[2017-04-26 10:57:00 DEBUG] (org.apache.http.wire:?) - http-outgoing-0 >> "Connection: keep-alive[\r][\n]" [2017-04-26 10:57:00 DEBUG] (org.apache.http.wire:?) - http-outgoing-0 >> "Keep-Alive: timeout=60[\r][\n]"## 服務端設置超時時間5s[2017-04-26 10:57:00 DEBUG] (org.apache.http.wire:?) - http-outgoing-0 << "Keep-Alive: timeout=5, max=100[\r][\n]"[2017-04-26 10:57:00 DEBUG] (org.apache.http.wire:?) - http-outgoing-0 << "Connection: Keep-Alive[\r][\n]" ## 服務端設置生效,連接可以保持5s[2017-04-26 10:57:00 DEBUG] (org.apache.http.impl.execchain.MainClientExec:?) - Connection can be kept alive for 5000 MILLISECONDS[2017-04-26 10:57:00 DEBUG] (org.apache.http.impl.conn.PoolingHttpClientConnectionManager:?) - Connection [id: 0][route: {}->http://bizdomain:80] can be kept alive for 5.0 seconds [2017-04-26 10:57:00 DEBUG] (org.apache.http.impl.conn.PoolingHttpClientConnectionManager:?) - Connection released: [id: 0][route: {}->http://bizdomain:80][total kept alive: 1; route allocated: 1 of 32; total allocated: 1 of 200]##Keep-Alive: timeout=60 非第一次請求[2017-04-26 14:11:00 DEBUG] (org.apache.http.impl.conn.PoolingHttpClientConnectionManager:?) - Connection request: [route: {}->http://bizdomain:80][total kept alive: 1; route allocated: 1 of 32; total allocated: 1 of 200]## 連接在上一次請求結束后5s失效[2017-04-26 14:11:00 DEBUG] (org.apache.http.impl.conn.CPool:?) - Connection [id:2][route:{}->http://bizdomain:80][state:null] expired @ Wed Apr 26 14:10:05 GMT+08:00 2017
客戶端設置失效時間,服務端設置不失效
## 客戶端設置30s超時[2017-04-26 17:45:00 DEBUG] (org.apache.http.wire:?) - http-outgoing-0 >> "Connection: keep-alive[\r][\n]" [2017-04-26 17:45:00 DEBUG] (org.apache.http.wire:?) - http-outgoing-0 >> "Keep-Alive: timeout=30[\r][\n]"## 服務端設置永久連接[2017-04-26 17:45:00 DEBUG] (org.apache.http.wire:?) - http-outgoing-0 << "Connection: keep-alive[\r][\n]" ## 連接將一直保持 [2017-04-26 17:45:00 DEBUG] (org.apache.http.impl.execchain.MainClientExec:?) - Connection can be kept alive indefinitely
綜上,http連接保持時間是由服務端的消息頭connection字段和keep-alive字段定的。
在上面前兩種情況,請求的是同一個服務端,那么為什么一個返回的是短連接,一個返回的是長連接呢?這里轉一下 這篇文章的解釋:
不論request還是response的header中包含了值為close的connection,都表明當前正在使用的tcp鏈接在請求處理完畢后會被斷掉。以后client再進行新的請求時就必須創建新的tcp鏈接了。 HTTP Connection的 close設置允許客戶端或服務器中任何一方關閉底層的連接,雙方都會要求在處理請求后關閉它們的TCP連接。
TCP長短連接
在網上搜資料的時候,看到很多“HTTP協議的長連接和短連接,實質上是TCP協議的長連接和短連接”。 HTTP和TCP是不同兩層的東西,它們怎么會是一樣的呢?HTTP是請求/響應模式的,就是說我們發一個請求一定要有一個回應。最直觀的就是,瀏覽器上發請求,得不到響應就會一直轉圈圈。 而TCP并不是一定要有響應。大家以前使用socket模擬一個IM聊天,A跟B打完招呼,完全可以不用等待B的回應,就自己關掉連接的。
TCP keep-alive
另外還有HTTP協議的keep-alive和TCP的keep-alive含義是有差別的。HTTP的keep-alive是為了維持連接,以便復用連接。通過使用keep-alive機制,可以減少tcp連接建立次數,也意味著可以減少TIME_WAIT狀態連接,以此提高性能和提高httpd服務器的吞吐率(更少的tcp連接意味著更少的系統內核調用,socket的accept()和close()調用)。但是,長時間的tcp連接容易導致系統資源無效占用。配置不當的keep-alive,有時比重復利用連接帶來的損失還更大。
而tcp keep-alive是TCP的一種檢測TCP連接狀況的機制,涉及到三個參數tcp_keepalive_time, tcp_keepalive_intvl, tcp_keepalive_probes。
當網絡兩端建立了TCP連接之后,閑置(雙方沒有任何數據流往來)了tcp_keepalive_time后,服務器內核就會嘗試向客戶端發送偵測包,來判斷TCP連接狀況(有可能客戶端崩潰、強制關閉了應用、主機不可達等等)。如果沒有收到對方的回答(ack包),則會在 tcp_keepalive_intvl后再次嘗試發送偵測包,直到收到對方的ack。如果一直沒有收到對方的ack,一共會嘗試 tcp_keepalive_probes次。如果嘗試tcp_keepalive_probes,依然沒有收到對方的ack包,則會丟棄該TCP連接。TCP連接默認閑置時間是2小時,一般設置為30分鐘足夠了
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。