OkHttp源码学习之ConnectionPool

241 阅读1分钟

connectionPool作用

ConnectionPool 即连接池,用来管理 HTTP 和 HTTP/2 连接的重用,以减少网络延迟 它的主要作用是:

连接复用:ConnectionPool 负责管理客户端与服务器之间的网络连接。它允许客户端重用已建立的连接,而不是为每个请求都创建一个新的连接,这可以减少TCP连接的建立和关闭的开销,提高性能。

连接超时:ConnectionPool 可以设置连接的超时时间,超过这个时间没有被使用的连接会被自动关闭,以回收系统资源。

连接限制:ConnectionPool 可以限制同时打开的连接数量,以防止过多的连接占用系统资源。

连接回收:当新的请求需要使用一个连接时,ConnectionPool 会首先检查是否有可用的空闲连接,如果有,则重用该连接;如果没有,则创建一个新的连接。

连接生命周期管理:ConnectionPool 负责管理连接的生命周期,包括连接的创建、分配和释放。


class ConnectionPool internal constructor(
  internal val delegate: RealConnectionPool
) {
  constructor(
    maxIdleConnections: Int,
    keepAliveDuration: Long,
    timeUnit: TimeUnit
  ) : this(RealConnectionPool(
      taskRunner = TaskRunner.INSTANCE,
      maxIdleConnections = maxIdleConnections, //最大空闲连接数量
      keepAliveDuration = keepAliveDuration,  //存活时间
      timeUnit = timeUnit
  ))

  constructor() : this(5, 5, TimeUnit.MINUTES)

  /** 返回池中的空闲连接数. */
  fun idleConnectionCount(): Int = delegate.idleConnectionCount()

  /** 线程池中所有的链接数量 */
  fun connectionCount(): Int = delegate.connectionCount()

  /** 移除连接池里所有的请求. */
  fun evictAll() {
    delegate.evictAll()
  }
}

连接池的参数设置

    val client = OkHttpClient.Builder()
    .connectionPool(ConnectionPool().apply {
        maxIdleConnections = 50 // 设置最大空闲连接数
        keepAliveDuration = 5, TimeUnit.MINUTES // 设置连接的最大空闲时间
    })
    .build()