【问题标题】:Apache HttpAsyncClient and CountDownLatchApache HttpAsyncClient 和 CountDownLatch
【发布时间】:2019-03-05 22:10:53
【问题描述】:

在使用 apache htttpasyncclient 时如何正确处理各种异常情况?考虑以下基于此example 的伪代码,其中我已将消费者参数添加到执行调用。目的是发出一个异步 http 请求,当字节进来时数据作为流处理,而不是在处理之前等待完整的响应完成。可能会出现各种问题,例如 http 请求的超时异常、连接失败(可能是没有网络)等。是否始终保证例如在响应未及时返回的超时时 releaseResources() 总是叫。问题是需要将latch.countDown() 放在下面的代码中的什么位置,以始终保证无论发生什么异常,await 调用都不会挂起。 StreamConsumer.releaseResources() 中对 latch.countDown() 的调用是否足以防止在等待时挂起?

public static void main(final String[] args) throws Exception {
    client.execute(HttpAsyncMethods.createGet(u), new StreamConsumer(...), new FutureCallback<Boolean>() {
        @Override
        public void cancelled() {
            // Is latch call needed here?
            // latch.countDown();
        }

        @Override
        public void completed(Boolean response) {
            // Is latch call needed here?
            // latch.countDown();
        }

        @Override
        public void failed(Exception e) {
            // Is latch call needed here?
            // latch.countDown();
        }
    });

    latch.await();
}


static class StreamConsumer extends AsyncByteConsumer<Boolean> {
    @Override
    protected void onResponseReceived(final HttpResponse response) {
       latch.countDown();
    }

    @Override
    protected void onByteReceived(final ByteBuffer buf, final IOControl ioctrl) throws IOException {

    }

    @Override
    protected void releaseResources() {
        latch.countDown();
    }

}

【问题讨论】:

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


    【解决方案1】:

    CloseableHttpAsyncClient#execute 方法在将请求提交到请求执行管道时立即终止,并返回一个代表未来操作结果的Future 对象。

    因此,示例中的闩锁需要确保客户端在CloseableHttpAsyncClient#execute 调用后不会立即关闭。

    如果将CloseableHttpAsyncClient 用作具有已定义生命周期(应该如此)的单例,则请求完成和客户端关闭的同步可能是不必要的。

    【讨论】:

      猜你喜欢
      • 2016-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-27
      相关资源
      最近更新 更多