我正在使用RestTemplate
HttpComponentsClientHttpRequestFactory
,如下所示:
private RestTemplate restTemplate = new RestTemplate();
// singleton class so only one instance
public DataProcess() {
restTemplate.setRequestFactory(clientHttpRequestFactory());
}
private ClientHttpRequestFactory clientHttpRequestFactory() {
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(1000).setConnectTimeout(1000)
.setSocketTimeout(1000).setStaleConnectionCheckEnabled(false).build();
PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager();
poolingHttpClientConnectionManager.setMaxTotal(300);
poolingHttpClientConnectionManager.setDefaultMaxPerRoute(300);
CloseableHttpClient httpClientBuilder = HttpClientBuilder.create()
.setConnectionManager(poolingHttpClientConnectionManager).setMaxConnPerRoute(300).setMaxConnTotal(300)
.setDefaultRequestConfig(requestConfig).build();
requestFactory.setHttpClient(httpClientBuilder);
return requestFactory;
}
现在我的问题是:在setMaxTotal
对象设置setDefaultMaxPerRoute
和PoolingHttpClientConnectionManager
与设置setMaxConnPerRoute
和{{1}之间有什么区别?在setMaxConnTotal
中。我是否需要在这两个地方设置这些?
还有其他设置我们应该与RestTemplate一起使用吗?我通过使用RestTemplate作为我的HttpClient调用Restful服务,因此它必须快速,因为此代码将在多线程应用程序中运行。
答案 0 :(得分:2)
如果您不提供默认池连接管理器,则构建器参数用于构建默认池连接管理器。因此,在您的示例中,构建器上的集合是多余的。
请参阅HttpClientBuilder(抱歉,我不得不将这个巨大的方法大量删除):
public CloseableHttpClient build() {
... snip ...
HttpClientConnectionManager connManagerCopy = this.connManager;
if (connManagerCopy == null) {
... snip ...
@SuppressWarnings("resource")
final PoolingHttpClientConnectionManager poolingmgr = new PoolingHttpClientConnectionManager(
RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", sslSocketFactoryCopy)
.build(),
null,
null,
null,
connTimeToLive,
connTimeToLiveTimeUnit != null ? connTimeToLiveTimeUnit : TimeUnit.MILLISECONDS);
... snip ...
if (maxConnTotal > 0) {
poolingmgr.setMaxTotal(maxConnTotal);
}
if (maxConnPerRoute > 0) {
poolingmgr.setDefaultMaxPerRoute(maxConnPerRoute);
}
connManagerCopy = poolingmgr;
}
... snip ...
return new InternalHttpClient(... snip ...);
}