我们经常在应用系统中使用httpclient来发送http请求,我们通常会new httpclient创建对象,这样,当请求并发量很大的时候,频繁的创建、销毁httpclient会导致不必要的性能开销,所以有必要对httpclient这个重量级对象进行池化。
在此,我们使用apache提供的common-pool包做相应的事情。
重要代码如下:
点击(此处)折叠或打开
-
public class HttpClientPool extends GenericObjectPool<HttpClient>{
-
//构造方法接受一个PoolableObjectFactory,来定义对象的创建
-
public HttpClientPool(PoolableObjectFactory<HttpClient> factory) {
-
super(factory);
-
}
-
-
//自定义
-
public <T> T doPost(HttpMethod method, HttpClientDataCallback<T> callback) {
-
HttpClient toUse = null;
-
try {
-
toUse = borrowObject();
-
toUse.executeMethod(method);
-
T rel = callback.handleResponse(method.getResponseBodyAsString());
-
return rel;
-
} catch (Exception e) {
-
logger.error(\"failed to execute http request.\", e);
-
return null;
-
} finally {
-
try {
-
method.releaseConnection();
-
} catch (Exception e) {
-
//in case fail, ignore and return object
-
}
-
if (toUse != null) {
-
try {
-
returnObject(toUse);
-
} catch (Exception e) {
-
logger.warn(\"failed to return http client\", e);
-
}
-
}
-
}
-
}
- }
PoolableHttpClientFactory:该类实现对池化对象的初始创建动作
点击(此处)折叠或打开
- public class PoolableHttpClientFactory implements PoolableObjectFactory<HttpClient> {
-
private int contimeout; //Connection time out
-
private int sotimeout; //so time out
-
-
public PoolableHttpClientFactory(int contimeout, int sotimeout) {
-
this.contimeout = contimeout;
-
this.sotimeout = sotimeout;
-
}
-
-
/*对象的生成在此定义
-
*(non-Javadoc)
-
* @see org.apache.commons.pool.PoolableObjectFactory#makeObject()
-
*/
-
@Override
-
public HttpClient makeObject() throws Exception {
-
HttpClient httpClient = new HttpClient();
-
HttpConnectionManagerParams configParams = httpClient.getHttpConnectionManager().getParams();
-
configParams.setConnectionTimeout(contimeout);
-
configParams.setSoTimeout(sotimeout);
-
httpClient.getParams().setConnectionManagerTimeout(contimeout);
-
httpClient.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, \"UTF-8\");
-
return httpClient;
-
}
- }
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/28912557/viewspace-1223241/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/28912557/viewspace-1223241/