每个主机或全局的OkHttp连接池maxIdleConnections?

时间:2014-10-11 18:51:15

标签: okhttp

  1. 同步使用HttpOk时。使用连接池的模式,maxIdleConnections是每个主机或全局限制吗?

    在源代码中,我可以看到一条评论说它是按地址但是我无法在公共文档(javadoc,wiki)中找到这些信息,而且在查看源代码时它似乎是全局的(我只看到connectionsCleanupRunnable使用它而不知道地址)。

  2. 如果所有"缓存"正在使用连接而另一个线程想要建立连接,将创建一个新连接吗?它会在交换结束时关闭还是被添加到连接池中,并在下次连接connectCleanupRunnable时关闭+清理?

  3. 谢谢:)

2 个答案:

答案 0 :(得分:2)

在okHTTP3中,连接池不再是全局的

Note: as of OkHttp3, it is recommended you declare this object as a singleton because changes in OkHttp3 no long require a global connection pool.

参考#https://guides.codepath.com/android/Using-OkHttp

There is no longer a global singleton connection pool. In OkHttp 2.x, all OkHttpClient instances shared a common connection pool by default. In OkHttp 3.x, each new OkHttpClient gets its own private connection pool. Applications should avoid creating many connection pools as doing so prevents connection reuse. Each connection pool holds its own set of connections alive so applications that have many pools also risk exhausting memory!

The best practice in OkHttp 3 is to create a single OkHttpClient instance and share it throughout the application. Requests that needs a customized client should call OkHttpClient.newBuilder() on that shared instance. This allows customization without the drawbacks of separate connection pools.

参考#https://github.com/amplitude/Amplitude-Android/issues/79

答案 1 :(得分:1)

每个主机。如果闲置连接已经在那里停留了5分钟,则会从池中删除空闲连接。