Java HTTP 客户端使用 Spring 初始化



我试图了解使用apaches HTTPPooledConnectionManager和Closeable HTTPClient的最佳方式。 我看到的所有示例似乎都在请求中创建了一个新的HTTPClient,并且没有关闭HttpClient。
它不应该是静态的还是按类的?如果可以重复使用具有池连接管理器的 HttpClient,并且连接被释放回池中,那么我们不是每次发出请求时都会创建 HttpClient 吗? 我想在基于 Spring 的框架中特别理解这一点。

这是一个示例代码,我认为HttpClient应该是静态的。

import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import java.io.IOException;
import java.net.URISyntaxException;
public class Stub2000  {
private CloseableHttpClient httpClient;
public void init()  {
RequestConfig config = RequestConfig.custom()
.setConnectTimeout(10000)
.setSocketTimeout(10000)
.setConnectionRequestTimeout(10000)
.build();
PoolingHttpClientConnectionManager poolManager = new PoolingHttpClientConnectionManager();
poolManager.setMaxTotal(10);
poolManager.setDefaultMaxPerRoute(10);
httpClient = HttpClients
.custom()
.setDefaultRequestConfig(config)
.setConnectionManager(poolManager)
.build();
}
public void getInfo() throws URISyntaxException, IOException {
final URIBuilder ruribuilder = new URIBuilder();
final HttpGet get = new HttpGet();
ruribuilder.setHost(host)
.setScheme("https")
.setPort(5555)
.setPath(uri)
.addParameter("txn",txn);
get.setURI(ruribuilder.build());
CloseableHttpResponse response = httpClient.execute(get);
try {
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
String result = EntityUtils.toString(response.getEntity());
}
else {
//Some Error
}
}catch(Exception e){
e.printStackTrace();
} finally {
EntityUtils.consume(response.getEntity());
}
}

每次发出请求时,我们都会创建一个池大小为 10 的新 HTTP客户端? 如果这是一个使用 spring 框架初始化的 bean,并且在 bean 初始化时调用了 init 方法,那么它是否只在 spring 初始化时或发出请求时执行一次?

它不应该是静态的还是每个类的?

  • 为了获得更好的性能,最好重用客户端。如何重用 - 使其静态或创建将注入的 Bean - 取决于您。有时您可能需要几个具有不同配置的不同客户端,即超时等。

如果可以重复使用具有池连接管理器的 HttpClient,并且连接被释放回池中,那么我们不是每次发出请求时都会创建 HttpClient 吗?

  • 连接管理器可以重复使用,这是可配置的。

每次发出请求时,我们都会创建一个池大小为 10 的新 HTTP客户端?

  • 使用默认配置 - 是的。

如果这是一个使用 spring 框架初始化的 bean,并且在 bean 初始化时调用了 init 方法,那么它是否只在 spring 初始化时或发出请求时执行一次?

  • 它不仅取决于创建一次的 bean,还取决于 http 客户端和连接管理器的配置

请参考 Spring RestTemplate - 需要释放连接? , http://www.baeldung.com/spring-scheduled-tasks

最新更新