這篇文章歸納了怎樣在多線程環境下安全的使用HttpClient。apache
MultiThreadedHttpConnectionManager安全
在HttpClient中使用多線程的一個主要緣由是能夠一次執行多個方法。在執行期間,每個方法都使用一個HttpConnection實例。因爲在同一時間多個鏈接只能安全地用於單一線程和方法和有限的資源,咱們就必須確保鏈接分配給正確的方法。而MultiThreadedHttpConnectionManager徹底能夠代替咱們完成這一項工做,這樣咱們就沒必要去考慮多線程帶來安全的問題。多線程
MultiThreadedHttpConnectionManager connectionManager =ide
new MultiThreadedHttpConnectionManager();線程
HttpClient client = new HttpClient(connectionManager);component
以上代碼中的HttpClient就在多線程中執行多個方法了。當咱們再次調用httpClient.executeMethod()方法時,就會去Connection Manager中去請求HttpConneciton的實例,這樣就避免了線程安全問題,由於HttpClient已經幫咱們作了。ci
Options資源
MultThreadedHttpConnectionManager參數配置:get
connectionStaleCheckingEnabled:這個標誌對全部已經建立的connections都適用。除特殊狀況外,此值應該設置成true。it
maxConnectionsPerHost:最大鏈接數,默認是2。
maxTotalConnections:最大活動鏈接數,默認是20。
釋放鏈接
connection management比較重要的是當鏈接再也不使用時,必定要手動釋放。這樣作的緣由是HttpClient不可以肯定哪一個方法不被使用,哪一個方法還在使用。這是由於Response body不是由HttpClient來自動讀取其數據的,而是由使用HttpClient的應用程序來完成的。當讀取Response的數據是時,必須使用此方法的鏈接。這樣,在Response的數據在讀取前,HttpClient是沒有釋放鏈接的。全部這就要求在讀取完Response的數據後,應用程序及時的使用releaseConnection()方法來釋放鏈接。
MultiThreadedHttpConnectionManager connectionManager =
new MultiThreadedHttpConnectionManager();
HttpClient client = new HttpClient(connectionManager);
...
// and then from inside some thread executing a method
GetMethod get = new GetMethod("http://httpcomponents.apache.org/");
try {
client.executeMethod(get);
// print response to stdout
System.out.println(get.getResponseBodyAsStream());
} finally {
// be sure the connection is released back to the connection
// manager
get.releaseConnection();
}
特別注意,不管執行的方法或是否也不例外被拋出。對於每個HttpClient.executeMethod方法必須有一個method.releaseConnection ( )來釋放鏈接。