httpClient创建
HttpClients.createDefault()实际上也是调用HttpClientBuilder.create().build()。
HttpClientConnectionManager
一个HTTP连接在某一时刻只被一个线程使用。
BasicHttpClientConnectionManager:每次只管理一个connection,一个线程调用。
PoolingHttpClientConnectionManager(默认):
其他
httpClient:
RequestConfig请求配置,各种超时设置;PoolingHttpClientConnectionManager连接池配置,各种连接池信息;
最终搞出个httpClient;
然后有个HttpComponentsClientHttpRequestFactory工厂类,生产httpClient。
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate() {
return new RestTemplate(httpRequestFactory());
}
public ClientHttpRequestFactory httpRequestFactory() {
return new HttpComponentsClientHttpRequestFactory(httpClient());
}
public HttpClient httpClient() {
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory> create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", SSLConnectionSocketFactory.getSocketFactory()).build();
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);
// 设置整个连接池最大连接数 根据自己的场景决定
connectionManager.setMaxTotal(100);
// 路由是对maxTotal的细分
connectionManager.setDefaultMaxPerRoute(100);
RequestConfig requestConfig = RequestConfig.custom()
// 服务器返回数据(response)的时间,超过该时间抛出read timeout
.setSocketTimeout(10000)
// 连接上服务器(握手成功)的时间,超出该时间抛出connect timeout
.setConnectTimeout(5000)
// 从连接池中获取连接的超时时间,超过该时间未拿到可用连接,
// 会抛出org.apache.http.conn.ConnectionPoolTimeoutException: Timeout waiting for connection from pool
.setConnectionRequestTimeout(1000).build();
return HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).setConnectionManager(connectionManager)
.build();
}
}
httpClient :
PoolingHttpClientConnectionManager:默认连接池最多20,每个route默认2,连接池取连接,连接建立,传输数据,默认无限等待。
httpClient资源释放,response记得释放。
response
EntityUtils.consume(entity)。
执行response.close()虽然会正确释放掉该connection占用的所有资源,但是这是一种比较暴力的方式,采用这种方式之后,这个connection就不能被重复使用了。
https://blog.csdn.net/guanglihuan/article/details/50521743