本文介绍了为什么我使用HttpClients.createDefault()作为HttpClient单例实例执行第三个请求总是挂起的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

全部,

我创建:

public static final HttpClient DEFAULT_HTTPCLIENT = HttpClients
        .createDefault();

for(int i=0 ; i<5; i++){
    DEFAULT_HTTPCLIENT.execute(requests[i]);
}

但是当循环到i = 2时,这意味着只执行前两个请求,直到执行第三个请求,客户端就会挂起,似乎是死循环.

But when loop is to i =2 , that means just execute first two request , till third request , the client will hang and seems dead loop .

我参考了一些资料,可能是由于Http Thread Pool配置受限所致.但是我知道该问题的标准解决方案是什么?由于我想随时发送任何请求,但是我不想每次都创建新的HttpClient.那么,您对此问题有任何好的标准建议吗?

I refer some materials , I got may be caused by Http Thread Pool configuration limited . But I know what is standard solutions for this issue ? Since I want to send any request any times, but I don't want each time to create new HttpClient . So Do you have any good and standard suggestions for this issue ?

,在调试完此问题后,我发现它在HttpClient上的代码如下: PoolingHttpClientConnectionManager-> leaseConnection-> entry = future.get(timeout,tunit);

and After I debug this issue , I find it is block on HttpClient below codes : PoolingHttpClientConnectionManager -> leaseConnection -> entry = future.get(timeout, tunit);

protected HttpClientConnection leaseConnection(
        final Future<CPoolEntry> future,
        final long timeout,
        final TimeUnit tunit) throws InterruptedException, ExecutionException,   ConnectionPoolTimeoutException {
    final CPoolEntry entry;
    try {
        entry = future.get(timeout, tunit);
        if (entry == null || future.isCancelled()) {
            throw new InterruptedException();
        }
        Asserts.check(entry.getConnection() != null, "Pool entry with no connection");
        if (this.log.isDebugEnabled()) {
            this.log.debug("Connection leased: " + format(entry) + formatStats(entry.getRoute()));
        }
        return CPoolProxy.newProxy(entry);
    } catch (final TimeoutException ex) {
        throw new ConnectionPoolTimeoutException("Timeout waiting for connection from pool");
    }
}

推荐答案

那是因为您的代码正在泄漏连接.默认情况下,HttpClient配置为同一路由最多允许两个并发连接,因此在完全耗尽该池之前,只需要执行两个请求即可.

That is because your code is leaking connections. By default HttpClient is configured to allow no more than two concurrent connections for the same route, hence it takes only two request executions before the pool is fully exhausted.

http://hc.apache.org/httpcomponents-client-ga/tutorial/html/fundamentals.html#d5e145

这篇关于为什么我使用HttpClients.createDefault()作为HttpClient单例实例执行第三个请求总是挂起的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 04:59