paulwong

          http connection存活期

          HTTP1.1的鏈接,默認是長鏈接,不會主動關閉。
          LINUX會默認保留鏈接5天再關閉。
          建立HTTP鏈接其實也是調用TCL的協議去建立,包括開始的時候有三次握手,關閉的時候有四次握手。關閉鏈接雙方都可以發起。
          但這些鏈接可能會被防火墻關掉而不通知建立鏈接的雙方,因此設置需設置鏈接的存活期。
          使用httpClient的鏈接池時,要設置池中的鏈接存活期或設置存活策略。
          檢測存活期只在每次發送數據時,才檢測取出的鏈接是否超過存活期,如超過則關閉。
          設置存活期的策略:

          import java.util.concurrent.TimeUnit;

          import org.apache.http.HeaderElement;
          import org.apache.http.HeaderElementIterator;
          import org.apache.http.HttpResponse;
          import org.apache.http.conn.ConnectionKeepAliveStrategy;
          import org.apache.http.message.BasicHeaderElementIterator;
          import org.apache.http.protocol.HTTP;
          import org.apache.http.protocol.HttpContext;
          import org.apache.http.util.Args;

          public class MyConnectionKeepAliveStrategy implements ConnectionKeepAliveStrategy{
              
              
              private int timeToLive;
              private TimeUnit timeUnit;

              public MyConnectionKeepAliveStrategy(int timeToLive, TimeUnit timeUnit) {
                  this.timeToLive = timeToLive;
                  this.timeUnit = timeUnit;
              }

              @Override
              public long getKeepAliveDuration(final HttpResponse response, final HttpContext context) {
                  Args.notNull(response, "HTTP response");
                  final HeaderElementIterator it = new BasicHeaderElementIterator(
                          response.headerIterator(HTTP.CONN_KEEP_ALIVE));
                  while (it.hasNext()) {
                      final HeaderElement he = it.nextElement();
                      final String param = he.getName();
                      final String value = he.getValue();
                      if (value != null && param.equalsIgnoreCase("timeout")) {
                          try {
                              return Long.parseLong(value) * 1000;
                          } catch(final NumberFormatException ignore) {
                              //do nothing
                          }
                      }
                  }
                  return timeUnit.toMillis(timeToLive);
              }

          }

          《HttpClient官方文檔》2.6 連接維持存活策略
          http://ifeve.com/httpclient-2-6/

          httpclient連接池管理,你用對了?
          http://ifeve.com/http-connection-pool/

          HttpClient連接池的一些思考
          https://zhuanlan.zhihu.com/p/85524697

          HTTP協議的Keep-Alive 模式
          https://www.jianshu.com/p/49551bda6619

          posted on 2020-12-31 15:08 paulwong 閱讀(359) 評論(0)  編輯  收藏 所屬分類: HTTPCLIENT

          主站蜘蛛池模板: 涿州市| 遂川县| 沁阳市| 昌宁县| 克拉玛依市| 三都| 凤凰县| 鸡东县| 商城县| 桃园市| 额济纳旗| 双辽市| 泗洪县| 洞口县| 镇安县| 奎屯市| 清河县| 绥阳县| 田东县| 金坛市| 河间市| 开阳县| 山东省| 万荣县| 尖扎县| 乐平市| 木里| 阜阳市| 呼图壁县| 嘉黎县| 临江市| 南宁市| 刚察县| 黑河市| 旺苍县| 蒲城县| 元谋县| 大英县| 会同县| 阳朔县| 永新县|