gpt4 book ai didi

httpclient - PoolingHttpClientConnectionManager 不重新使用现有的空闲连接

转载 作者:行者123 更新时间:2023-12-02 03:51:42 30 4
gpt4 key购买 nike

我正在使用 Apache PoolingHttpClientConnectionManager 创建连接池。但是我在日志中看到现有的空闲连接未使用,而是创建了一个新连接。下面是代码

PoolingHttpClientConnectionManager connManager = connManager = new PoolingHttpClientConnectionManager();
connManager.setMaxTotal(4);
connManager.setDefaultMaxPerRoute(4);

//Creating CloseableHttpClient with a default keep alive of 2 minutes
CloseableHttpClient client = HttpClients.custom()
.setConnectionManager(connManager)
.setKeepAliveStrategy(new KeepAliveStrategy(keepAlive))
.build();


//Sending 1st request
String xml="<xml data>";
HttpPost post = new HttpPost("<URL>");
HttpEntity entity = new ByteArrayEntity(xml.getBytes("UTF-8"));
post.setEntity(entity);
HttpResponse response =client.execute(post);
String result = EntityUtils.toString(response.getEntity());
EntityUtils.consume(response.getEntity());

收到响应后,PoolStats 显示可用连接总数为 1

现在,我在 5 秒后再次触发相同的请求,在收到响应后,PoolStats 指出可用连接总数为 2

以下代码适用于PoolStats

 PoolStats stats = connManager.getTotalStats();
System.out.println("Total Connections Available : "+stats.getAvailable());

My Question here is Since after the First Request-response there was already a Connection in the pool so why did it create one more connection. Why it did not use the existing conenction?

最佳答案

问题是因为我在这里使用 SSL,所以默认情况下不允许 SSL 上下文共享相同的连接。这就是为什么它为每个请求创建另一个连接。该解决方案创建自定义 UserTokenHandler 并将其分配给连接管理器。

UserTokenHandler userTokenHandler = new UserTokenHandler() {

@Override
public Object getUserToken(final HttpContext context) {
return context.getAttribute("my-token");
}

};

client = HttpClients.custom()
.setConnectionManager(connManager)
.setUserTokenHandler(userTokenHandler)
.setKeepAliveStrategy(new KeepAliveStrategy(keepAlive))
.build();

关于httpclient - PoolingHttpClientConnectionManager 不重新使用现有的空闲连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45214720/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com