How to configure the number of allowed pending requests in Apache async client

耗尽温柔 提交于 2019-12-06 09:37:09

Apache HttpAsyncClient maintains an unbounded request execution queue and does not attempt to limit the number of pending requests. Various applications may or may not want to throttle request rate and there is no easy way to satisfy them all.

One can however fairly easily throttle the number of concurrent requests using a simple semaphore.

final Semaphore semaphore = new Semaphore(maxConcurrencyLevel);
for (int i = 0; i < n; i++) {

    semaphore.acquire();
    this.httpclient.execute(
            new BasicAsyncRequestProducer(target, request),
            new MyResponseConsumer(),
            new FutureCallback<HttpResponse>() {

                @Override
                public void completed(final HttpResponse result) {
                    semaphore.release();
                }

                @Override
                public void failed(final Exception ex) {
                    semaphore.release();
                }

                @Override
                public void cancelled() {
                    semaphore.release();
                }

            });
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!