佳木斯湛栽影视文化发展公司

主頁(yè) > 知識(shí)庫(kù) > HTTP長(zhǎng)連接與短連接使用方法及測(cè)試詳解

HTTP長(zhǎng)連接與短連接使用方法及測(cè)試詳解

熱門標(biāo)簽:鐵路電話系統(tǒng) 網(wǎng)站文章發(fā)布 智能手機(jī) 檢查注冊(cè)表項(xiàng) 呼叫中心市場(chǎng)需求 銀行業(yè)務(wù) 美圖手機(jī) 服務(wù)器配置

HTTP短連接(非持久連接)是指,客戶端和服務(wù)端進(jìn)行一次HTTP請(qǐng)求/響應(yīng)之后,就關(guān)閉連接。所以,下一次的HTTP請(qǐng)求/響應(yīng)操作就需要重新建立連接。

HTTP長(zhǎng)連接(持久連接)是指,客戶端和服務(wù)端建立一次連接之后,可以在這條連接上進(jìn)行多次請(qǐng)求/響應(yīng)操作。持久連接可以設(shè)置過(guò)期時(shí)間,也可以不設(shè)置。

我為什么沒(méi)有說(shuō)HTTP/1.0 默認(rèn)短連接,HTTP/1.1起,默認(rèn)長(zhǎng)連接呢?因?yàn)槲业谝淮慰催@個(gè)說(shuō)法的時(shí)候,以為自己懂了,其實(shí)并沒(méi)有懂。長(zhǎng)短連接操作上有什么區(qū)別,有的地方出現(xiàn)的持久連接又是怎么回事?

使用設(shè)置

這里的設(shè)置,我們都以HTTP1.1協(xié)議為例子。

設(shè)置HTTP短連接

在首部字段中設(shè)置Connection:close,則在一次請(qǐng)求/響應(yīng)之后,就會(huì)關(guān)閉連接。

設(shè)置HTTP長(zhǎng)連接,有過(guò)期時(shí)間

在首部字段中設(shè)置Connection:keep-alive 和Keep-Alive: timeout=60,表明連接建立之后,空閑時(shí)間超過(guò)60秒之后,就會(huì)失效。如果在空閑第58秒時(shí),再次使用此連接,則連接仍然有效,使用完之后,重新計(jì)數(shù),空閑60秒之后過(guò)期。

設(shè)置HTTP長(zhǎng)連接,無(wú)過(guò)期時(shí)間

在首部字段中只設(shè)置Connection:keep-alive,表明連接永久有效。

實(shí)現(xiàn)原理

了解怎么設(shè)置之后,就開(kāi)始用起來(lái)。然而,問(wèn)題來(lái)了。在請(qǐng)求頭中設(shè)置Connection:keep-alive,為什么連接空閑一段時(shí)間之后,還是斷開(kāi)了呢?這是因?yàn)閏onnection字段只有服務(wù)端設(shè)置才有效。

HTTP操作是請(qǐng)求/響應(yīng)成對(duì)出現(xiàn)的,即先有客戶端發(fā)出請(qǐng)求,后有服務(wù)端處理請(qǐng)求。所以,一次HTTP操作的終點(diǎn)操作在服務(wù)端上,關(guān)閉也是由服務(wù)端發(fā)起的。

接下來(lái)我們做做測(cè)試,以及show code。下面的測(cè)試都是使用Spring RestTemplate,封裝apache http client進(jìn)行的。為方便講解代碼,先說(shuō)明長(zhǎng)連接的情況,最后再對(duì)其他形式做測(cè)試總結(jié)。

客戶端連接失效時(shí)間大于服務(wù)端失效時(shí)間

如下,為請(qǐng)求日志??蛻舳嗽O(shè)置Connection: Keep-Alive和Keep-Alive: timeout=60, 服務(wù)端設(shè)置Connection: Keep-Alive和Keep-Alive: timeout=5。

## 客戶端設(shè)置有效期為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"
##服務(wù)端設(shè)置有效期為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"

客戶端設(shè)置的有效期大于服務(wù)端的,那么實(shí)際連接的有效期呢?三分鐘之后再次請(qǐng)求,從連接池中l(wèi)ease連接的時(shí)候,提示Connection expired @ Wed Apr 26 14:08:05,即在上一次請(qǐng)求之后的5s失效,說(shuō)明是服務(wù)端的設(shè)置生效了。

[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

源碼分析

通過(guò)源代碼了解一下連接失效時(shí)間的設(shè)置過(guò)程。

//org.apache.http.impl.execchain.MainClientExec#execute
......
//從連接池中l(wèi)ease connection
final 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設(shè)置為close,則返回false
if (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);
  }
  //設(shè)置失效時(shí)間
  connHolder.setValidFor(duration, TimeUnit.MILLISECONDS);
  connHolder.markReusable();
} else {
  connHolder.markNonReusable();
}

待讀取響應(yīng)之后,釋放連接,即:connHolder.releaseConnection()。調(diào)用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);
          //設(shè)置失效時(shí)間
          entry.updateExpiry(keepalive, effectiveUnit);
        }
      } finally {
      。。。。。。
        }
      }
    }
  }

然后再下一次HTTP操作,從連接池中獲取連接時(shí)

//org.apache.http.impl.conn.PoolingHttpClientConnectionManager#requestConnection調(diào)用org.apache.http.pool.AbstractConnPool#lease,
//調(diào)用getPoolEntryBlocking,調(diào)用org.apache.http.impl.conn.CPoolEntry#isExpired
@Override
public boolean isExpired(final long now) {
  final boolean expired = super.isExpired(now);
  if (expired  this.log.isDebugEnabled()) {
  //日志中看到的內(nèi)容
    this.log.debug("Connection " + this + " expired @ " + new Date(getExpiry()));
  }
  return expired;
}

綜上,連接的實(shí)際有效時(shí)間,是根據(jù)response的設(shè)置來(lái)決定的。

其他情況測(cè)試

客戶端設(shè)置Connection: Close

##connection:close請(qǐng)求,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
## 客戶端設(shè)置短連接
[2017-04-26 13:57:00 DEBUG] (org.apache.http.wire:?) - http-outgoing-0 >> "Connection: Close[\r][\n]"
## 服務(wù)端返回的也是短連接
[2017-04-26 13:57:00 DEBUG] (org.apache.http.wire:?) - http-outgoing-0  "Connection: close[\r][\n]"
##請(qǐng)求完之后,關(guā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]

如上,當(dāng)服務(wù)端返回Connection: Close時(shí),客戶端接收完響應(yīng),便會(huì)關(guān)閉連接。

客戶端設(shè)置60s超時(shí),服務(wù)端設(shè)置5s超時(shí)

##Keep-Alive: timeout=60 第一次請(qǐng)求,與connection:close無(wú)差別
[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
## 客戶端設(shè)置超時(shí)時(shí)間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]"
## 服務(wù)端設(shè)置超時(shí)時(shí)間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]"
## 服務(wù)端設(shè)置生效,連接可以保持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 非第一次請(qǐng)求
[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]
## 連接在上一次請(qǐng)求結(jié)束后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

客戶端設(shè)置失效時(shí)間,服務(wù)端設(shè)置不失效

## 客戶端設(shè)置30s超時(shí)
[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]"
## 服務(wù)端設(shè)置永久連接
[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連接保持時(shí)間是由服務(wù)端的消息頭connection字段和keep-alive字段定的。

在上面前兩種情況,請(qǐng)求的是同一個(gè)服務(wù)端,那么為什么一個(gè)返回的是短連接,一個(gè)返回的是長(zhǎng)連接呢?這里轉(zhuǎn)一下 這篇文章的解釋:

不論request還是response的header中包含了值為close的connection,都表明當(dāng)前正在使用的tcp鏈接在請(qǐng)求處理完畢后會(huì)被斷掉。以后client再進(jìn)行新的請(qǐng)求時(shí)就必須創(chuàng)建新的tcp鏈接了。 HTTP Connection的 close設(shè)置允許客戶端或服務(wù)器中任何一方關(guān)閉底層的連接,雙方都會(huì)要求在處理請(qǐng)求后關(guān)閉它們的TCP連接。

補(bǔ)充

TCP長(zhǎng)短連接

在網(wǎng)上搜資料的時(shí)候,看到很多“HTTP協(xié)議的長(zhǎng)連接和短連接,實(shí)質(zhì)上是TCP協(xié)議的長(zhǎng)連接和短連接”。 HTTP和TCP是不同兩層的東西,它們?cè)趺磿?huì)是一樣的呢?HTTP是請(qǐng)求/響應(yīng)模式的,就是說(shuō)我們發(fā)一個(gè)請(qǐng)求一定要有一個(gè)回應(yīng)。最直觀的就是,瀏覽器上發(fā)請(qǐng)求,得不到響應(yīng)就會(huì)一直轉(zhuǎn)圈圈。 而TCP并不是一定要有響應(yīng)。大家以前使用socket模擬一個(gè)IM聊天,A跟B打完招呼,完全可以不用等待B的回應(yīng),就自己關(guān)掉連接的。

TCP keep-alive

另外還有HTTP協(xié)議的keep-alive和TCP的keep-alive含義是有差別的。HTTP的keep-alive是為了維持連接,以便復(fù)用連接。通過(guò)使用keep-alive機(jī)制,可以減少tcp連接建立次數(shù),也意味著可以減少TIME_WAIT狀態(tài)連接,以此提高性能和提高h(yuǎn)ttpd服務(wù)器的吞吐率(更少的tcp連接意味著更少的系統(tǒng)內(nèi)核調(diào)用,socket的accept()和close()調(diào)用)。但是,長(zhǎng)時(shí)間的tcp連接容易導(dǎo)致系統(tǒng)資源無(wú)效占用。配置不當(dāng)?shù)膋eep-alive,有時(shí)比重復(fù)利用連接帶來(lái)的損失還更大。

而tcp keep-alive是TCP的一種檢測(cè)TCP連接狀況的機(jī)制,涉及到三個(gè)參數(shù)tcp_keepalive_time, tcp_keepalive_intvl, tcp_keepalive_probes。

當(dāng)網(wǎng)絡(luò)兩端建立了TCP連接之后,閑置(雙方?jīng)]有任何數(shù)據(jù)流往來(lái))了tcp_keepalive_time后,服務(wù)器內(nèi)核就會(huì)嘗試向客戶端發(fā)送偵測(cè)包,來(lái)判斷TCP連接狀況(有可能客戶端崩潰、強(qiáng)制關(guān)閉了應(yīng)用、主機(jī)不可達(dá)等等)。如果沒(méi)有收到對(duì)方的回答(ack包),則會(huì)在 tcp_keepalive_intvl后再次嘗試發(fā)送偵測(cè)包,直到收到對(duì)方的ack。如果一直沒(méi)有收到對(duì)方的ack,一共會(huì)嘗試 tcp_keepalive_probes次。如果嘗試tcp_keepalive_probes,依然沒(méi)有收到對(duì)方的ack包,則會(huì)丟棄該TCP連接。TCP連接默認(rèn)閑置時(shí)間是2小時(shí),一般設(shè)置為30分鐘足夠了。

更多關(guān)于HTTP長(zhǎng)連接與短連接使用方法請(qǐng)查看下面的相關(guān)鏈接

您可能感興趣的文章:
  • 詳談python http長(zhǎng)連接客戶端
  • 頁(yè)面間隔半秒鐘更新時(shí)間 Asp.net使用Comet開(kāi)發(fā)http長(zhǎng)連接示例分享
  • 基于HTTP長(zhǎng)連接的"服務(wù)器推"技術(shù)的php 簡(jiǎn)易聊天室

標(biāo)簽:河南 上海 沈陽(yáng) 滄州 長(zhǎng)治 紅河 新疆 樂(lè)山

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《HTTP長(zhǎng)連接與短連接使用方法及測(cè)試詳解》,本文關(guān)鍵詞  ;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問(wèn)題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無(wú)關(guān)。
  • 相關(guān)文章
  • 收縮
    • 微信客服
    • 微信二維碼
    • 電話咨詢

    • 400-1100-266
    敦煌市| 洪泽县| 邳州市| 苏尼特右旗| 犍为县| 兴国县| 柏乡县| 历史| 台南市| 南郑县| 乌苏市| 峡江县| 阿拉善右旗| 容城县| 吉林省| 清苑县| 龙川县| 南和县| 平阳县| 关岭| 寻乌县| 亳州市| 宝山区| 白水县| 涞源县| 襄城县| 本溪市| 丽水市| 同德县| 咸丰县| 陈巴尔虎旗| 嘉荫县| 灌阳县| 丹凤县| 峡江县| 朝阳区| 桐梓县| 福泉市| 航空| 嘉禾县| 沧州市|