Apache HttpAsyncClient和CountDownLatch

问题描述 投票:0回答:1

使用apache htttpasyncclient时如何正确处理各种异常情况?考虑以下基于此example的伪代码,其中我已将consumer参数添加到execute调用。目的是创建异步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个回答
0
投票

CloseableHttpAsyncClient#execute方法在向请求执行管道提交请求后立即终止,并返回表示操作的未来结果的Future对象。

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

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

© www.soinside.com 2019 - 2024. All rights reserved.