httpclient的池化

541732025發表於2014-07-20

我們經常在應用系統中使用httpclient來傳送http請求,我們通常會new httpclient建立物件,這樣,當請求併發量很大的時候,頻繁的建立、銷燬httpclient會導致不必要的效能開銷,所以有必要對httpclient這個重量級物件進行池化。
在此,我們使用apache提供的common-pool包做相應的事情。
重要程式碼如下:

點選(此處)摺疊或開啟

  1. public class HttpClientPool extends GenericObjectPool<HttpClient>{
  2.      //構造方法接受一個PoolableObjectFactory,來定義物件的建立
  3.     public HttpClientPool(PoolableObjectFactory<HttpClient> factory) {
  4.         super(factory);
  5.     }

  6.     //自定義
  7.     public <T> T doPost(HttpMethod method, HttpClientDataCallback<T> callback) {
  8.         HttpClient toUse = null;
  9.         try {
  10.             toUse = borrowObject();
  11.             toUse.executeMethod(method);
  12.             T rel = callback.handleResponse(method.getResponseBodyAsString());
  13.             return rel;
  14.         } catch (Exception e) {
  15.             logger.error(\"failed to execute http request.\", e);
  16.             return null;
  17.         } finally {
  18.             try {
  19.                 method.releaseConnection();
  20.             } catch (Exception e) {
  21.                 //in case fail, ignore and return object
  22.             }
  23.             if (toUse != null) {
  24.                 try {
  25.                     returnObject(toUse);
  26.                 } catch (Exception e) {
  27.                     logger.warn(\"failed to return http client\", e);
  28.                 }
  29.             }
  30.         }
  31.     }
  32. }


PoolableHttpClientFactory:該類實現對池化物件的初始建立動作

點選(此處)摺疊或開啟

  1. public class PoolableHttpClientFactory implements PoolableObjectFactory<HttpClient> {
  2.     private int contimeout; //Connection time out
  3.     private int sotimeout; //so time out

  4.     public PoolableHttpClientFactory(int contimeout, int sotimeout) {
  5.         this.contimeout = contimeout;
  6.         this.sotimeout = sotimeout;
  7.     }

  8.     /*物件的生成在此定義
  9.      *(non-Javadoc)
  10.      * @see org.apache.commons.pool.PoolableObjectFactory#makeObject()
  11.      */
  12.     @Override
  13.     public HttpClient makeObject() throws Exception {
  14.         HttpClient httpClient = new HttpClient();
  15.         HttpConnectionManagerParams configParams = httpClient.getHttpConnectionManager().getParams();
  16.         configParams.setConnectionTimeout(contimeout);
  17.         configParams.setSoTimeout(sotimeout);
  18.         httpClient.getParams().setConnectionManagerTimeout(contimeout);
  19.         httpClient.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, \"UTF-8\");
  20.         return httpClient;
  21.     }
  22. }



來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/28912557/viewspace-1223241/,如需轉載,請註明出處,否則將追究法律責任。

相關文章