【问题标题】:HttpAsyncClient isn't making request if setConnectionManagerShared is set to true如果 setConnectionManagerShared 设置为 true,则 HttpAsyncClient 不会发出请求
【发布时间】:2015-09-07 17:05:59
【问题描述】:

如果setConnectionManagerShared 设置为true,由于某种原因HttpAsyncClient 不会发出请求。我找到了这个bug,但不知道我错过了什么。

这是我创建新客户的方法

def apply(proxy: Option[HttpHost], cookieStore: Option[CookieStore]) = {

val builder = HttpAsyncClients.custom.
  setConnectionManager(connManager).
  setConnectionManagerShared(true).
  setDefaultCredentialsProvider(credentialsProvider).
  setDefaultRequestConfig(defaultRequestConfig).
  setSSLStrategy(sslStrategy)

proxy.map(builder.setProxy)
builder.setDefaultCookieStore(cookieStore.getOrElse(new BasicCookieStore)) // Use custom cookie store if necessary.

// Create an HttpClient with the given custom dependencies and configuration.
val client: HttpAsyncClient = new HttpAsyncClient(builder.build)
client
}

全班位于here

我应该改变什么?

【问题讨论】:

    标签: apache-httpclient-4.x apache-commons-httpclient asynchttpclient apache-httpasyncclient


    【解决方案1】:
    DefaultConnectingIOReactor ioReactor = new DefaultConnectingIOReactor();
    PoolingNHttpClientConnectionManager cm = new PoolingNHttpClientConnectionManager(ioReactor);
    
    CloseableHttpAsyncClient client1 = HttpAsyncClients.custom()
            .setConnectionManager(cm)
            .build();
    CloseableHttpAsyncClient client2 = HttpAsyncClients.custom()
            .setConnectionManager(cm)
            .setConnectionManagerShared(true)
            .build();
    
    client1.start();
    client2.start();
    
    final CountDownLatch latch = new CountDownLatch(2);
    FutureCallback callback = new FutureCallback<HttpResponse>() {
        @Override
        public void completed(HttpResponse result) {
            latch.countDown();
            System.out.println(result.getStatusLine());
        }
    
        @Override
        public void failed(Exception ex) {
            latch.countDown();
            System.out.println(ex.getMessage());
        }
    
        @Override
        public void cancelled() {
            latch.countDown();
        }
    };
    
    client1.execute(new HttpGet("http://httpbin.org/get"), callback);
    client2.execute(new HttpGet("http://httpbin.org/get"), callback);
    latch.await();
    
    // I am aware this is sloppy
    client1.close();
    client2.close();
    

    【讨论】:

    • 谢谢!是否有可能因为我为每个创建的客户端都调用setConnectionManagerShared 而无法正常工作?如果是,这是否意味着我需要“拥有”非封闭式客户?
    • 应该有一个服务负责启动和关闭底层I/O反应器。由一个“拥有”连接管理器的客户端更容易完成,但也可以完全独立完成。
    • 知道了。我会在我的单身人士中保留一个虚拟客户。不过,这对我来说似乎有点骇人听闻。
    • 正如我所说,您不需要这样做。您还可以在单​​例中维护 IOReactor 实例并控制其生命周期。
    猜你喜欢
    • 2021-10-22
    • 2013-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多