【问题标题】:How can I make concurrent requests faster with Retrofit / OkHttp?如何使用 Retrofit / OkHttp 更快地发出并发请求?
【发布时间】:2017-06-17 01:19:36
【问题描述】:

我需要在 Android 中使用 Retrofit 尽快发出 50 个 http GET 请求。我正在使用带有 OkHttp 的改造。目前,Retrofit 与普通 Java ThreadPoolExecutorHttpUrlConnection 相比做得很差:对于所有 50 个请求,Retrofit 大约需要 50 秒,普通 HttpUrlConnection 大约需要 30 秒,如果我为 ThreadPoolExecutor 和 Retrofit / OkHttp 设置池大小 20我设置了okHttpClient.dispatcher().setMaxRequests(20);

如果我查看 logcat,我可以看到无论我在 setMaxRequests() 中设置什么,Retrofit 最多执行 5 个并发请求,而在 ThreadPoolExecutor 中,并发请求的数量与可用的工作线程一样多。

我可以做些什么来加快改造速度?我不想切换到HttpUrlConnection,因为 Retrofit 非常优雅且易于使用。

编辑 1

我尝试向 OkHttp 提供自定义 ThreadPoolExecutor,但没有时间改进:

OkHttpClient.Builder builder = new OkHttpClient.Builder();
ExecutorService exec = new ThreadPoolExecutor(20, 20, 1, TimeUnit.HOURS, new LinkedBlockingQueue<>());
Dispatcher d = new Dispatcher(exec);
builder.dispatcher(d);
OkHttpClient okHttpClient = builder.build();
okHttpClient.dispatcher().setMaxRequests(20);

编辑 2

如果这很重要,我会向同一个端点发出所有请求

【问题讨论】:

  • 我会考虑将其作为错误请求发布在这里:github.com/square/retrofit 希望从开发人员那里得到一些反馈
  • 您好,请问您为解决此问题做了哪些工作?无论我们设置多少默认为 5 个连接,甚至都面临同样的问题

标签: java android http retrofit okhttp3


【解决方案1】:

既然都去同一个主机,你试过了吗:

okHttpClient.dispatcher().setMaxRequestsPerHost(20);

Dispatcher.setMaxRequestsPerHost

【讨论】:

    猜你喜欢
    • 2017-06-09
    • 2017-11-07
    • 2019-12-08
    • 2014-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多