《Effective Java》—— 创建与销毁对象 一章中有写道:当一个类中有大量的构造参数时,静态方法和构造器已经不能满足对象的实例化,那么我们将考虑构建器。
builder模式十分灵活,可以利用单个builder构建多个对象。builder的参数可以在创建对象期间进行调整,也可以随着不同的对象而改变。
class DefaultHttpClientFactory {
private static PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
private static RequestConfig defaultRequestConfig = RequestConfig.custom().build();
private static int mgrMaxTotal = DEFAULT_MAX_TOTAL; //全局最大连接数
private static int mgrDefaultMaxPerRoute = DEFAULT_MAX_PER_ROUTE; //每个主机最大连接数
private static int connReqTimeout = DEFAULT_CONN_REQ_TIMEOUT; //从连接池获取连接超时时间
private static int connTimout = DEFAULT_CONN_TIMEOUT; //发起连接超时时间
private static int connSocketTimeout = DEFAULT_CONN_SOCKET_TIMEOUT; //连接套接字等待时间
public static class Builder {
private int mgrMaxTotal = DEFAULT_MAX_TOTAL; //全局最大连接数
private int mgrDefaultMaxPerRoute = DEFAULT_MAX_PER_ROUTE; //每个主机最大连接数
private int connReqTimeout = DEFAULT_CONN_REQ_TIMEOUT; //从连接池获取连接超时时间
private int connTimout = DEFAULT_CONN_TIMEOUT; //发起连接超时时间
private int connSocketTimeout = DEFAULT_CONN_SOCKET_TIMEOUT; //连接套接字等待时间
Builder() {
}
public Builder maxTotal(int maxTotal) {
this.mgrMaxTotal = maxTotal;
return this;
}
public Builder maxPerRoute(int maxPerRoute) {
this.mgrDefaultMaxPerRoute = maxPerRoute;
return this;
}
public Builder connReqTimeout(int connReqTimeout) {
this.connReqTimeout = connReqTimeout;
return this;
}
public Builder connTimout(int connTimout) {
this.connTimout = connTimout;
return this;
}
public Builder connSocketTimeout(int connSocketTimeout) {
this.connSocketTimeout = connSocketTimeout;
return this;
}
public DefaultHttpClientFactory build() {
return new DefaultHttpClientFactory(this);
}
}
private DefaultHttpClientFactory(Builder builder) {
mgrMaxTotal = builder.mgrMaxTotal;
mgrDefaultMaxPerRoute = builder.mgrDefaultMaxPerRoute;
connReqTimeout = builder.connReqTimeout;
connTimout = builder.connTimout;
connSocketTimeout = builder.connSocketTimeout;
}
public static DefaultHttpClientFactory.Builder custom() {
return new DefaultHttpClientFactory.Builder();
}
public CloseableHttpClient getClient() {
cm.setMaxTotal(mgrMaxTotal); // 设置最大连接数
cm.setDefaultMaxPerRoute(mgrDefaultMaxPerRoute); // 设置每个路由最大连接数,每个独立的host为1个路由
RequestConfig requestConfig = RequestConfig.copy(defaultRequestConfig)
.setConnectionRequestTimeout(connReqTimeout)//从连接池获取连接超时时间
.setConnectTimeout(connTimout)//发起连接超时时间
.setSocketTimeout(connSocketTimeout)//连接套接字等待时间
.setRedirectsEnabled(false)
.build();
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
httpClientBuilder.setConnectionManager(cm);
httpClientBuilder.setDefaultRequestConfig(requestConfig);
httpClientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(0, false)); // 去掉默认的3次重试
CloseableHttpClient httpClient = httpClientBuilder.build();
return httpClient;
}
}