HttpClient高級進階-ConnectionManager

簡述

本文介紹HttpClient的鏈接管理,主要介紹使用BasichttpClientConnectionManager和PoolingHttpClientConnectionManager來實現強制安全,協議兼容和有效使用HTTP鏈接。java

用於單線程鏈接的BasicHttpClientConnectionManager

自HttpClient 4.3.3起,BasicHttpClientConnectionManager可用做HTTP鏈接管理器的最簡單實現。它用於建立和管理一次只能由一個線程使用的單個鏈接。安全

獲取低級別鏈接的鏈接請求(HttpClientConnection)bash

BasicHttpClientConnectionManager connManager
 = new BasicHttpClientConnectionManager();
HttpRoute route = new HttpRoute(new HttpHost("http://localhost:8080", 80));
ConnectionRequest connRequest = connManager.requestConnection(route, null);

複製代碼

requestConnection方法從connManager獲得的鏈接池的特定路線來鏈接。該路線參數指定的「代理跳」到目標主機或目標主機自己的路由。服務器

能夠直接使用HttpClientConnection執行請求,但請記住,這種低級方法很冗長且難以管理。低級鏈接對於socket和http(如超時和目標主機信息)頗有用,但對於標準執行,HttpClient是一個更容易使用的API。多線程

使用PoolingHttpClientConnectionManager獲取和管理多線程鏈接池

該PoolingHttpClientConnectionManager將建立並管理咱們使用的每一個路線或目標主機的鏈接池。首先,讓咱們看看如何在一個簡單的HttpClient上設置這個鏈接管理器:併發

在HttpClient上設置PoolingHttpClientConnectionManagersocket

HttpClientConnectionManager poolingConnManager
  = new PoolingHttpClientConnectionManager();
CloseableHttpClient client
 = HttpClients.custom().setConnectionManager(poolingConnManager)
 .build();
client.execute(new HttpGet("/"));
assertTrue(poolingConnManager.getTotalStats().getLeased() == 1);
複製代碼

接下來,讓咱們看看兩個不一樣線程中運行的兩個HttpClient如何使用相同的ConnectionManager:ide

使用兩個HttpClient鏈接到每一個目標主機ui

HttpGet get1 = new HttpGet("");
HttpGet get2 = new HttpGet(""); 
PoolingHttpClientConnectionManager connManager 
  = new PoolingHttpClientConnectionManager(); 
CloseableHttpClient client1 
  = HttpClients.custom().setConnectionManager(connManager).build();
CloseableHttpClient client2 
  = HttpClients.custom().setConnectionManager(connManager).build();
 
MultiHttpClientConnThread thread1
 = new MultiHttpClientConnThread(client1, get1); 
MultiHttpClientConnThread thread2
 = new MultiHttpClientConnThread(client2, get2); 
thread1.start();
thread2.start();
thread1.join();
thread2.join();
複製代碼

請注意,咱們使用的是一個很是簡單的自定義線程實現,這裏是:this

自定義線程執行 GET請求

public class MultiHttpClientConnThread extends Thread {
    private CloseableHttpClient client;
    private HttpGet get;
     
    // standard constructors
    public void run(){
        try {
            HttpResponse response = client.execute(get);  
            EntityUtils.consume(response.getEntity());
        } catch (ClientProtocolException ex) {    
        } catch (IOException ex) {
        }
    }
}
複製代碼

請注意EntityUtils.consume(response.getEntity)調用,必須使用響應的所有內容(實體),以便manager能夠將鏈接釋放回池中。

配置ConnectionManager

ConnectionManager默認配置選擇很好,可是,根據你的使用狀況,會存在可能過小的狀況,那麼,讓咱們來看看咱們如何配置:

  • 鏈接總數
  • 每條(任何)路由的最大鏈接數
  • 每條特定路由的最大鏈接數

增長能夠打開和管理的鏈接數超出默認限制

PoolingHttpClientConnectionManager connManager 
  = new PoolingHttpClientConnectionManager();
connManager.setMaxTotal(5);
connManager.setDefaultMaxPerRoute(4);
HttpHost host = new HttpHost("www.baeldung.com", 80);
connManager.setMaxPerRoute(new HttpRoute(host), 5);
複製代碼

讓咱們回顧一下API:

  • setMaxTotal(int max):設置最大總打開鏈接數。
  • setDefaultMaxPerRoute(int max):設置每條路由的最大併發鏈接數,默認爲2。
  • setMaxPerRoute(int max):設置指向特定路由的併發鏈接總數,默認爲2。

所以,在不更改默認值的狀況下,咱們將很容易地達到鏈接管理器的限制 。讓咱們看看它是如何看起來的:

使用線程執行鏈接

HttpGet get = new HttpGet("http://localhost:8080");

PoolingHttpClientConnectionManager connManager 
  = new PoolingHttpClientConnectionManager();
CloseableHttpClient client = HttpClients.custom().
    setConnectionManager(connManager).build();
MultiHttpClientConnThread thread1 
  = new MultiHttpClientConnThread(client, get);
MultiHttpClientConnThread thread2 
  = new MultiHttpClientConnThread(client, get);
MultiHttpClientConnThread thread3 
  = new MultiHttpClientConnThread(client, get);
thread1.start();
thread2.start();
thread3.start();
thread1.join();
thread2.join();
thread3.join();
複製代碼

正如咱們已經討論過的,默認狀況下每主機鏈接限制爲2。所以,在此示例中,咱們嘗試讓3個線程向同一主機發出3個請求,但只會並行分配2個鏈接。

讓咱們來看看日誌 - 咱們有三個線程正在運行,但只有2個線程鏈接:

[Thread-0] INFO  o.b.h.c.MultiHttpClientConnThread
 - Before - Leased Connections = 0
[Thread-1] INFO  o.b.h.c.MultiHttpClientConnThread
 - Before - Leased Connections = 0
[Thread-2] INFO  o.b.h.c.MultiHttpClientConnThread
 - Before - Leased Connections = 0
[Thread-2] INFO  o.b.h.c.MultiHttpClientConnThread
 - After - Leased Connections = 2
[Thread-0] INFO  o.b.h.c.MultiHttpClientConnThread
 - After - Leased Connections = 2
複製代碼

長鏈接策略

引用HttpClient 4.3.3。reference:「 若是Keep-Alive響應中沒有標頭,HttpClient假定鏈接能夠無限期保持活動。」。

爲了解決這個問題,而且可以管理死鏈接,咱們須要一個自定義的策略實現並將其構建到HttpClient中。

自定義保持長鏈接策略

ConnectionKeepAliveStrategy myStrategy = new ConnectionKeepAliveStrategy() {
    @Override
    public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
        HeaderElementIterator it = new BasicHeaderElementIterator
            (response.headerIterator(HTTP.CONN_KEEP_ALIVE));
        while (it.hasNext()) {
            HeaderElement he = it.nextElement();
            String param = he.getName();
            String value = he.getValue();
            if (value != null && param.equalsIgnoreCase
               ("timeout")) {
                return Long.parseLong(value) * 1000;
            }
        }
        return 5 * 1000;
    }
};
複製代碼

此策略將首先嚐試應用標題中所述的主機的Keep-Alive策略。若是響應頭中不存在該信息,則它將保持活動鏈接5秒。

如今,讓咱們用這個自定義策略建立一個客戶端:

PoolingHttpClientConnectionManager connManager 
  = new PoolingHttpClientConnectionManager();
CloseableHttpClient client = HttpClients.custom()
  .setKeepAliveStrategy(myStrategy)
  .setConnectionManager(connManager)
  .build();
複製代碼

鏈接持久性/重用

HTTP / 1.1規範規定,若是鏈接還沒有關閉,則能夠從新使用鏈接 - 這稱爲鏈接持久性。

一旦管理員發佈鏈接,它就會保持開放狀態以便重複使用。使用只能管理單個鏈接的BasicHttpClientConnectionManager時,必須先釋放鏈接,而後再將其從新租用:

BasicHttpClientConnectionManager 鏈接重用

BasicHttpClientConnectionManager basicConnManager = 
    new BasicHttpClientConnectionManager();
HttpClientContext context = HttpClientContext.create();
 
// low level
HttpRoute route = new HttpRoute(new HttpHost("", 80));
ConnectionRequest connRequest = basicConnManager.requestConnection(route, null);
HttpClientConnection conn = connRequest.get(10, TimeUnit.SECONDS);
basicConnManager.connect(conn, route, 1000, context);
basicConnManager.routeComplete(conn, route, context);
 
HttpRequestExecutor exeRequest = new HttpRequestExecutor();
context.setTargetHost((new HttpHost("", 80)));
HttpGet get = new HttpGet("");
exeRequest.execute(get, conn, context);
 
basicConnManager.releaseConnection(conn, null, 1, TimeUnit.SECONDS);
 
// high level
CloseableHttpClient client = HttpClients.custom()
  .setConnectionManager(basicConnManager)
  .build();
client.execute(get);
複製代碼

咱們來看看會發生什麼。

首先 - 注意咱們首先使用低級鏈接,這樣咱們就能夠徹底控制鏈接什麼時候釋放,而後是與HttpClient的正常更高級別鏈接。複雜的低級邏輯在這裏並非很相關 - 咱們惟一關心的是releaseConnection調用。這將釋放惟一可用的鏈接並容許重用。

而後,客戶端再次成功執行GET請求。若是咱們跳過釋放鏈接,咱們將從HttpClient獲取IllegalStateException:

java.lang.IllegalStateException: Connection is still allocated
  at o.a.h.u.Asserts.check(Asserts.java:34)
  at o.a.h.i.c.BasicHttpClientConnectionManager.getConnection
    (BasicHttpClientConnectionManager.java:248)
複製代碼

請注意,現有鏈接未關閉,只是釋放,而後由第二個請求從新使用。

與上面的示例相反,PoolingHttpClientConnectionManager容許透明地鏈接重用,而無需隱式釋放鏈接:

PoolingHttpClientConnectionManager:從新使用與線程的鏈接

HttpGet get = new HttpGet("");
PoolingHttpClientConnectionManager connManager 
  = new PoolingHttpClientConnectionManager();
connManager.setDefaultMaxPerRoute(5);
connManager.setMaxTotal(5);
CloseableHttpClient client = HttpClients.custom()
  .setConnectionManager(connManager)
  .build();
MultiHttpClientConnThread[] threads 
  = new  MultiHttpClientConnThread[10];
for(int i = 0; i < threads.length; i++){
    threads[i] = new MultiHttpClientConnThread(client, get, connManager);
}
for (MultiHttpClientConnThread thread: threads) {
     thread.start();
}
for (MultiHttpClientConnThread thread: threads) {
     thread.join(1000);     
}
複製代碼

上面的示例有10個線程,執行10個請求但只共享5個鏈接。

固然,這個例子依賴於服務器的Keep-Alive超時。爲確保鏈接在從新使用以前不會死亡,建議使用Keep-Alive策略配置客戶端。

使用Connection Manager配置超時-Socket

配置鏈接管理器時惟一能夠設置的超時是Socket:

將Socket超時設置爲5秒

HttpRoute route = new HttpRoute(new HttpHost("http://localhost:8080", 80));
PoolingHttpClientConnectionManager connManager 
  = new PoolingHttpClientConnectionManager();
connManager.setSocketConfig(route.getTargetHost(),SocketConfig.custom().
    setSoTimeout(5000).build());
複製代碼

鏈接監控

鏈接斷開用於檢測空閒和過時鏈接並關閉它們 ; 有兩種選擇能夠作到這一點。

在執行請求以前依賴HttpClient來檢查鏈接是否異常。這是一個耗時的選擇,並不老是最優的。

建立監視器線程以關閉空閒和/或關閉的鏈接。

設置HttpClient以檢查過期鏈接

PoolingHttpClientConnectionManager connManager 
  = new PoolingHttpClientConnectionManager();
CloseableHttpClient client = HttpClients.custom().setDefaultRequestConfig(
    RequestConfig.custom().setStaleConnectionCheckEnabled(true).build()
).setConnectionManager(connManager).build();
複製代碼

使用異常的鏈接監視器線程

PoolingHttpClientConnectionManager connManager 
  = new PoolingHttpClientConnectionManager();
CloseableHttpClient client = HttpClients.custom()
  .setConnectionManager(connManager).build();
IdleConnectionMonitorThread staleMonitor
 = new IdleConnectionMonitorThread(connManager);
staleMonitor.start();
staleMonitor.join(1000);
複製代碼

該IdleConnectionMonitorThread 類列舉以下:

public class IdleConnectionMonitorThread extends Thread {
    private final HttpClientConnectionManager connMgr;
    private volatile boolean shutdown;
 
    public IdleConnectionMonitorThread(
      PoolingHttpClientConnectionManager connMgr) {
        super();
        this.connMgr = connMgr;
    }
    @Override
    public void run() {
        try {
            while (!shutdown) {
                synchronized (this) {
                    wait(1000);
                    connMgr.closeExpiredConnections();
                    connMgr.closeIdleConnections(30, TimeUnit.SECONDS);
                }
            }
        } catch (InterruptedException ex) {
            shutdown();
        }
    }
    public void shutdown() {
        shutdown = true;
        synchronized (this) {
            notifyAll();
        }
    }
}
複製代碼

鏈接關閉

能夠正常關閉鏈接(嘗試在關閉以前刷新輸出緩衝區),或經過調用shutdown方法(未刷新輸出緩衝區)強制關閉鏈接。

要正確關閉鏈接,咱們須要執行如下全部操做:

  • 消耗並關閉響應(若是能夠關閉)
  • 關閉客戶端
  • 關閉並關閉鏈接管理器

關閉鏈接和釋放資源

connManager = new PoolingHttpClientConnectionManager();
CloseableHttpClient client = HttpClients.custom()
  .setConnectionManager(connManager).build();
HttpGet get = new HttpGet("");
CloseableHttpResponse response = client.execute(get);
 
EntityUtils.consume(response.getEntity());
response.close();
client.close();
connManager.close();
複製代碼

若是管理器在沒有鏈接關閉的狀況下關閉,全部鏈接都將關閉並釋放全部資源。

重要的是要記住,這不會刷新現有鏈接可能正在進行的任何數據。

結論

在本文中,咱們討論瞭如何使用HttpClient的HTTP ConnectionManager API來處理管理鏈接的整個過程,從打開和分配鏈接,管理多個代理的併發使用,到最終關閉它們。

咱們看到BasicHttpClientConnectionManager是一個處理單個鏈接的簡單解決方案,以及它如何管理低級鏈接。咱們還了解了PoolingHttpClientConnectionManager如何與HttpClient API 結合使用,以提供HTTP鏈接的高效且協議兼容的使用。

相關文章
相關標籤/搜索