org.kaizen4j.common.httpclient.HttpClientProxyFactoryBean Maven / Gradle / Ivy
package org.kaizen4j.common.httpclient;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.client.StandardHttpRequestRetryHandler;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.kaizen4j.common.httpclient.interceptor.GZIPHttpResponseInterceptor;
import org.springframework.beans.factory.FactoryBean;
import com.google.common.base.Preconditions;
/**
* HttpClientProxy 的工厂 Bean。使用示例:
*
*
* {@code
*
*
*
*
*
*
* }
*
*/
public final class HttpClientProxyFactoryBean implements FactoryBean {
private int maxPerRoute;
// 单位毫秒
private int timeoutMills;
private int requestRetryCount;
public int getMaxPerRoute() {
return maxPerRoute;
}
public void setMaxPerRoute(int maxPerRoute) {
this.maxPerRoute = maxPerRoute;
}
public int getTimeoutMills() {
return timeoutMills;
}
public void setTimeoutMills(int timeoutMills) {
this.timeoutMills = timeoutMills;
}
public int getRequestRetryCount() {
return requestRetryCount;
}
public void setRequestRetryCount(int requestRetryCount) {
this.requestRetryCount = requestRetryCount;
}
/*
* @throws Exception
*
* @see org.springframework.beans.factory.FactoryBean#getObject()
*/
@Override
public HttpClientProxy getObject() throws Exception {
Preconditions.checkArgument(0 != maxPerRoute && 0 != timeoutMills);
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
connectionManager.setDefaultMaxPerRoute(maxPerRoute);
RequestConfig requestConfig =
RequestConfig.custom().setConnectionRequestTimeout(timeoutMills).setConnectTimeout(timeoutMills)
.setSocketTimeout(timeoutMills).setContentCompressionEnabled(true).build();
boolean requestSentRetryEnabled = (0 != requestRetryCount) ? true : false;
HttpRequestRetryHandler httpRequestRetryHandler =
new StandardHttpRequestRetryHandler(requestRetryCount, requestSentRetryEnabled);
CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig)
.setConnectionManager(connectionManager).setRetryHandler(httpRequestRetryHandler)
.addInterceptorFirst(new GZIPHttpResponseInterceptor()).build();
return new HttpClientProxy(httpClient);
}
/*
* @see org.springframework.beans.factory.FactoryBean#getObjectType()
*/
@Override
public Class getObjectType() {
return HttpClientProxy.class;
}
/*
* @see org.springframework.beans.factory.FactoryBean#isSingleton()
*/
@Override
public boolean isSingleton() {
return true;
}
}