Java 使用 Retrofit 的并行 HTTP 请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23255523/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 21:32:35  来源:igfitidea点击:

Parallel HTTP requests with Retrofit

javaandroidrestretrofit

提问by Vektor88

I have an Android application that is currently using Volleylibrary to make network requests and show downloaded images with NetworkImageView.

我有一个 Android 应用程序,该应用程序当前正在使用Volley库来发出网络请求并使用NetworkImageView.

I would like to test Retrofit's capabilities and since I need to run lots of requests (thousands) I'm a bit concerned about the parallel execution. Volleyhandles parallel requests with the RequestQueuethat limits the concurrent running requests to four, while the other requests are enqueued waiting to be executed. In Retrofitdocumentations I haven't found any way to handle the number of concurrent requests and I suspect that such details are left to the developer in this library.

我想测试Retrofit的功能,并且由于我需要运行大量请求(数千个),因此我有点担心并行执行。Volley处理并行请求,将RequestQueue并发运行请求限制为四个,而其他请求则排队等待执行。在Retrofit文档中,我没有找到任何方法来处理并发请求的数量,我怀疑这些细节留给了这个库中的开发人员。

Is this correct? If so, is there any android-oriented implementation/library available? Otherwise, what are the best practices to handle parallel requests?

这样对吗?如果是这样,是否有任何面向 android 的实现/库可用?否则,处理并行请求的最佳实践是什么?

采纳答案by Jake Wharton

Retrofit uses an Executorfor queueing requests.

Retrofit 使用 anExecutor来排队请求。

The default uses Executors.newCachedThreadPoolwhich allows for unlimited threads. This fits most use cases since normally you would only ever have one or two requests happening at once.

默认使用Executors.newCachedThreadPool允许无限线程。这适合大多数用例,因为通常您一次只会发生一两个请求。

You can change this behavior, however, by supplying your own when building the RestAdapter. Call setExecutorsand pass in an executor that uses a confined thread pool (limited to whatever number you would like). For the second argument, simply pass a new instance of MainThreadExecutorso that callbacks happen on the main thread.

但是,您可以通过在构建RestAdapter. 调用setExecutors并传入使用受限线程池的执行程序(限制为您想要的任何数量)。对于第二个参数,只需传递一个新实例,MainThreadExecutor以便在主线程上发生回调。