我有两个模板配置。一个是通过PoolightPClientConnectionManager配置连接,另一个是通过httpclientbuilder直接配置。两者都使用httpclient进行与连接相关的配置。
下面是一个 HttpClientBuilder
```
final HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
httpClientBuilder.setMaxConnTotal(maxConnPerRoute);
httpClientBuilder.setMaxConnPerRoute(maxConnPerRoute);
httpClientBuilder.setConnectionReuseStrategy(new NoConnectionReuseStrategy());
final HttpComponentsClientHttpRequestFactory httpComponentsClientHttpRequestFactory
= new HttpComponentsClientHttpRequestFactory();
httpComponentsClientHttpRequestFactory.setConnectTimeout(connectionTimeout);
httpComponentsClientHttpRequestFactory.setReadTimeout(connectionTimeout);
httpComponentsClientHttpRequestFactory.setHttpClient(httpClientBuilder.build());
final BufferingClientHttpRequestFactory bufferingClientHttpRequestFactory =
new BufferingClientHttpRequestFactory(httpComponentsClientHttpRequestFactory);
final RestTemplate restTemplate = new RestTemplate(bufferingClientHttpRequestFactory);
这里我们直接设置httpclient
httpComponentsClientHttpRequestFactory.setHttpClient(httpClientBuilder.build());
下面是 `PoolingHttpClientConnectionManager` ```
private ClientHttpRequestFactory clientHttpRequestFactory(final ConnectionPooling connectionPooling) {
final PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
connectionManager.setDefaultMaxPerRoute(connectionPooling.getMaxConnections());
connectionManager.setMaxTotal(connectionPooling.getMaxConnections());
final HttpClient httpclient = HttpClientBuilder
.create()
.setConnectionManager(connectionManager)
.build();
final HttpComponentsClientHttpRequestFactory connectionFactory =
new HttpComponentsClientHttpRequestFactory(httpclient);
connectionFactory.setConnectTimeout(connectionPooling.getConnectionTimeout());
connectionFactory.setReadTimeout(connectionPooling.getReadTimeout());
connectionFactory.setConnectionRequestTimeout(connectionPooling.getConnectionRequestTimeoutMillis());
final IdleConnectionEvictor idleConnectionTimeoutThread =
new IdleConnectionEvictor(connectionManager,
connectionPooling.getIdleConnectionCheckMillis(), TimeUnit.MILLISECONDS,
connectionPooling.getIdleConnectionTimeoutMillis(), TimeUnit.MILLISECONDS);
idleConnectionTimeoutThread.start();
return new BufferingClientHttpRequestFactory(connectionFactory);
}
在这里,我们设置像
final HttpClient httpclient = HttpClientBuilder
.create()
.setConnectionManager(connectionManager)
.build();
这两种配置有什么区别?两者的React会不同吗?
1条答案
按热度按时间vuv7lop31#
他们会有不同的表现。因为您的第一个httpclientbuilder没有设置连接管理器,所以它是线程不安全的。有一个像第二个例子那样的连接管理器是很有用的,原因很多。apache文档将连接管理器的好处概括如下:
http连接管理器的目的是充当新http连接的工厂,管理持久连接的生命周期,并同步对持久连接的访问,确保一次只能有一个线程访问一个连接。