【问题标题】:Retrofit2 - OkHttp ConnectionPool threads grows to 100+ threads. Why?Retrofit2 - OkHttp ConnectionPool 线程增长到 100 多个线程。为什么?
【发布时间】:2017-07-31 21:02:08
【问题描述】:

我在 java 服务上使用 retrofit2 连接到 REST API 并获取数据。

代码如下:

Retrofit retrofit =
        new Retrofit.Builder().baseUrl(endPoint).addConverterFactory(JacksonConverterFactory.create())
                              .build();

SyncCentralLojaProxySvc svc = retrofit.create(SyncCentralLojaProxySvc.class);

LogVerCentralLojaEntity entity = syncSvc.getLogVerByCdFilial(filial);
long cd_log = (entity != null) ? entity.getCdLog() : 0;

Call<LogCentralLojaCompactoCollectionDto> call = svc.getLogCompacto(filial, cd_log);

Response<LogCentralLojaCompactoCollectionDto> response = call.execute();

//NOT_MODIFIED
if (response.code() == 304) {
    return 0;
}

if (!response.isSuccessful())
    throw new IOException(response.errorBody().string());

LogCentralLojaCompactoCollectionDto body = response.body();

它是一个简单的数据获取,每隔几秒同步(非并行)运行一次。

我通过 VisualVM 注意到 OkHttp 线程增长过多。该应用程序永远不会同时使用 100 个操作。事实上,它只需要一个。

如何调整这个?有这么多线程是自然的吗?

【问题讨论】:

  • 这不正常。您是否正在创建一个 Retrofit 实例并重用它?还是为每个请求创建一个?
  • 我正在为每个请求创建一个,但将其更改为仅创建一个请求并没有帮助,它仍然会创建相同的线程。

标签: retrofit2 okhttp


【解决方案1】:

使用连接池配置设置全局客户端解决了这个问题:

ConnectionPool pool = new ConnectionPool(5, 10000, TimeUnit.MILLISECONDS);

OkHttpClient client = new OkHttpClient.Builder()
                              .connectionPool(pool)
                              .build();

Retrofit retrofit =
        new Retrofit.Builder().baseUrl(endPoint)
                              .client(client)
                              .addConverterFactory(JacksonConverterFactory.create())
                              .build();

【讨论】:

  • 10 秒对于保持活动的持续时间可能太小了。 OkHttp 默认使用 5 分钟。
猜你喜欢
  • 2018-11-12
  • 2015-11-28
  • 2010-09-20
  • 2014-07-21
  • 2022-01-23
  • 1970-01-01
  • 2012-05-14
  • 2016-10-29
  • 1970-01-01
相关资源
最近更新 更多