我们经常在应用系统中使用httpclient来发送http请求,我们通常会new httpclient创建对象,这样,当请求并发量很大的时候,频繁的创建、销毁httpclient会导致不必要的性能开销,所以有必要对httpclient这个重量级对象进行池化。
在此,我们使用apache提供的common-pool包做相应的事情。
重要代码如下:
public class HttpClientPool extends GenericObjectPool{
//构造方法接受一个PoolableObjectFactory,来定义对象的创建
public HttpClientPool(PoolableObjectFactory factory) {
super(factory);
}
//自定义
public T doPost(HttpMethod method, HttpClientDataCallback 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 {
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;
}
}
网友评论