Retrofit2 - OkHttp ConnectionPool线程增长到100多个线程.为什么?

Thi*_*yão 6 okhttp retrofit2

我在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();
Run Code Online (Sandbox Code Playgroud)

它是一个简单的数据获取,每隔几秒就会同步(不是并行)运行.

我注意到,通过VisualVM,OkHttp thredas增长得太多了.该应用程序永远不会并行使用100个操作.实际上,它只需要一个.

我该如何调整?拥有这么多线程是很自然的吗?

VisualVM线程监视器

Thi*_*yão 7

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

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();
Run Code Online (Sandbox Code Playgroud)

  • 10 秒对于保持活动持续时间来说可能太小了。OkHttp 默认使用 5 分钟。 (2认同)