网络库OKHttp(1)流程

news2024/9/20 9:33:55

序、慢慢来才是最快的方法。

背景

OkHttp 是一套处理 HTTP 网络请求的依赖库,由 Square 公司设计研发并开源,目前可以在 Java 和 Kotlin 中使用。对于 Android App 来说,OkHttp 现在几乎已经占据了所有的网络请求操作。

OKHttp源码官网  

版本

api 'com.squareup.okhttp3:okhttp:4.10.0'

发起网络请求示例代码

  val  okHttpClient = OkHttpClient()
        val request :Request = Request.Builder()
            .url("")
            .build()

        val newCall = okHttpClient.newCall(request)
        //同步请求
        newCall.execute()
        //异步请求
        newCall.enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                TODO("Not yet implemented")
            }

            override fun onResponse(call: Call, response: Response) {
                TODO("Not yet implemented")
            }
        })

核心类

OkHttpClient 、Request 、Call 、RealCall 、Dispatcher 、Deque 、AsyncCall 、Response  

  • OkHttpClient: Okhttp用于请求的执行客户端
  • Request: 通过Bulider设计模式,构建的一个请求对象
  • Call: 是通过 client.newCall 生成的请求执行对象,当执行了execute之后才会真正的开始执行网络请求
  • Response: 是通过网络请求后,从服务器返回的信息都在里面。内含返回的状态码,以及代表响应消息正文的ResponseBody
  1. interceptor 用户定义的拦截器,在重试拦截器之前执行
  2. retryAndFollowUpInterceptor 重试拦截器
  3. BridgeInterceptor 建立网络桥梁的拦截器,主要是为了给网络请求时候,添加各种各种必要参数。如Cookie,Content-type
  4. CacheInterceptor 缓存拦截器,主要是为了在网络请求时候,根据返回码处理缓存。
  5. ConnectInterceptor 连接拦截器,主要是为了从连接池子中查找可以复用的socket连接。
  6. networkInterceptors 用户定义的网络拦截器,在CallServerInterceptor(执行网络请求拦截器)之前运行。
  7. CallServerInterceptor 真正执行网络请求的逻辑。

1.网路请求流程

OkHttpClient 网络配置层

class Builder constructor() {
   //Okhttp 请求分发器,是整个OkhttpClient的执行核心
  internal var dispatcher: Dispatcher = Dispatcher()
  //Okhttp连接池,不过会把任务委托给RealConnectionPool处理
  internal var connectionPool: ConnectionPool = ConnectionPool()
  //用户定义的拦截器,在重试拦截器之前执行
  internal val interceptors: MutableList<Interceptor> = mutableListOf()
  //用户定义的网络拦截器,在CallServerInterceptor(执行网络请求拦截器)之前运行。
  internal val networkInterceptors: MutableList<Interceptor> = mutableListOf()
  //流程监听器
  internal var eventListenerFactory: EventListener.Factory = EventListener.NONE.asFactory()
  //连接失败时是否重连
  internal var retryOnConnectionFailure = true
  //服务器认证设置
  internal var authenticator: Authenticator = Authenticator.NONE
  //是否重定向
  internal var followRedirects = true
  //是否重定向到https
  internal var followSslRedirects = true
  //cookie持久化的设置
  internal var cookieJar: CookieJar = CookieJar.NO_COOKIES
  //缓存设置
  internal var cache: Cache? = null
  //DNS设置
  internal var dns: Dns = Dns.SYSTEM
  //代理设置
  internal var proxy: Proxy? = null
  internal var proxySelector: ProxySelector? = null
  internal var proxyAuthenticator: Authenticator = Authenticator.NONE
  //默认的socket连接池
  internal var socketFactory: SocketFactory = SocketFactory.getDefault()
  //用于https的socket连接池
  internal var sslSocketFactoryOrNull: SSLSocketFactory? = null
  //用于信任Https证书的对象
  internal var x509TrustManagerOrNull: X509TrustManager? = null
  internal var connectionSpecs: List<ConnectionSpec> = DEFAULT_CONNECTION_SPECS
  //http协议集合
  internal var protocols: List<Protocol> = DEFAULT_PROTOCOLS
  //https对host的检验
  internal var hostnameVerifier: HostnameVerifier = OkHostnameVerifier
  internal var certificatePinner: CertificatePinner = CertificatePinner.DEFAULT
  internal var certificateChainCleaner: CertificateChainCleaner? = null
  //请求超时
  internal var callTimeout = 0
  //连接超时
  internal var connectTimeout = 10_000
  //读取超时
  internal var readTimeout = 10_000
  //写入超时
  internal var writeTimeout = 10_000
  internal var pingInterval = 0
  internal var minWebSocketMessageToCompress = RealWebSocket.DEFAULT_MINIMUM_DEFLATE_SIZE
  internal var routeDatabase: RouteDatabase? = null
  }

client.newCall(request):

override fun newCall(request: Request): Call = RealCall(this, request, forWebSocket = false)

在这里生成一个RealCall对象,这里第三个参数是否为websocket,默认是false。 在拿到RealCall对象之后,这里有两种方式起发送网络请求:

  • execute() : 这种方式很少用
  • enqueue() : 这种方式是将每个请求放在队列中,按照顺序逐个去进行消费。

RealCall.enqueue()

override fun enqueue(responseCallback: Callback) {
  check(executed.compareAndSet(false, true)) { "Already Executed" }

  callStart()
  client.dispatcher.enqueue(AsyncCall(responseCallback))
}


private fun callStart() {
  this.callStackTrace = Platform.get().getStackTraceForCloseable("response.body().close()")
  eventListener.callStart(this)
}

这里主要做了一下几步

  • 首先回调eventListener的callStart()方法,
  • 然后把创建AsyncCall对象将responseCallback传进去。
  • 最后Dispatcher的enqueue()方法.

Dispatcher.enqueue()


class Dispatcher constructor() {

    ......

//按运行顺序准备异步调用的队列
private val readyAsyncCalls = ArrayDeque<AsyncCall>()

//正在运行的异步请求队列, 包含取消但是还未finish的AsyncCall
private val runningAsyncCalls = ArrayDeque<AsyncCall>()

//正在运行的同步请求队列, 包含取消但是还未finish的RealCall
private val runningSyncCalls = ArrayDeque<RealCall>()

    ......
    
internal fun enqueue(call: AsyncCall) {
  synchronized(this) {
    readyAsyncCalls.add(call)

  
    if (!call.call.forWebSocket) {
      val existingCall = findExistingCallWithHost(call.host)
      if (existingCall != null) call.reuseCallsPerHostFrom(existingCall)
    }
  }
  promoteAndExecute()
}

private fun findExistingCallWithHost(host: String): AsyncCall? {
  for (existingCall in runningAsyncCalls) {
    if (existingCall.host == host) return existingCall
  }
  for (existingCall in readyAsyncCalls) {
    if (existingCall.host == host) return existingCall
  }
  return null
}

  • 首先将AsyncCall加入readyAsyncCalls队列中.
  • 然后通过findExistingCallWithHost查找在runningAsyncCalls和readyAsyncCalls是否存在相同host的AsyncCall,如果存在则调用call.reuseCallsPerHostFrom()进行复用
  • 最后调用 promoteAndExecute() 通过线程池执行队列中的AsyncCall对象

Dispatcher.promoteAndExecute()

private fun promoteAndExecute(): Boolean {
  this.assertThreadDoesntHoldLock()

  val executableCalls = mutableListOf<AsyncCall>()
    //判断是否有请求正在执行
  val isRunning: Boolean
   //加锁,保证线程安全
  synchronized(this) {
   //遍历 readyAsyncCalls 队列
    val i = readyAsyncCalls.iterator()
    while (i.hasNext()) {
      val asyncCall = i.next()
       //runningAsyncCalls的数量不能大于最大并发请求数 64
      if (runningAsyncCalls.size >= this.maxRequests) break // Max capacity.
      //同一Host的最大数是5
      if (asyncCall.callsPerHost.get() >= this.maxRequestsPerHost) continue // Host max capacity.
       //从readyAsyncCalls队列中移除并加入到executableCalls和runningAsyncCalls中
      i.remove()
      asyncCall.callsPerHost.incrementAndGet()
      executableCalls.add(asyncCall)
      runningAsyncCalls.add(asyncCall)
    }
    isRunning = runningCallsCount() > 0
  }
    //遍历executableCalls 执行asyncCall
  for (i in 0 until executableCalls.size) {
    val asyncCall = executableCalls[i]
    asyncCall.executeOn(executorService)
  }

  return isRunning
}

在这里遍历readyAsyncCalls队列,判断runningAsyncCalls的数量是否大于最大并发请求数64, 判断同一Host的请求是否大于5,然后将AsyncCall从readyAsyncCalls队列中移除,并加入到executableCalls和runningAsyncCalls中,遍历executableCalls 执行asyncCall.

RealCall.AsyncCall.exceuteOn()

internal inner class AsyncCall(
  private val responseCallback: Callback
) : Runnable {

     ......

  fun executeOn(executorService: ExecutorService) {
    client.dispatcher.assertThreadDoesntHoldLock()

    var success = false
    try {
       //执行AsyncCall 的run方法
      executorService.execute(this)
      success = true
    } catch (e: RejectedExecutionException) {
      val ioException = InterruptedIOException("executor rejected")
      ioException.initCause(e)
      noMoreExchanges(ioException)
      responseCallback.onFailure(this@RealCall, ioException)
    } finally {
      if (!success) {
        client.dispatcher.finished(this) // This call is no longer running!
      }
    }
  }

  override fun run() {
    threadName("OkHttp ${redactedUrl()}") {
      var signalledCallback = false
      timeout.enter()
      try {
         //执行OkHttp的拦截器  获取response对象
        val response = getResponseWithInterceptorChain()
        signalledCallback = true
        //通过该方法将response对象回调出去
        responseCallback.onResponse(this@RealCall, response)
      } catch (e: IOException) {
        if (signalledCallback) {
  
          Platform.get().log("Callback failure for ${toLoggableString()}", Platform.INFO, e)
        } else {
            //遇到IO异常  回调失败方法
          responseCallback.onFailure(this@RealCall, e)
        }
      } catch (t: Throwable) {
         //遇到其他异常  回调失败方法
        cancel()
        if (!signalledCallback) {
          val canceledException = IOException("canceled due to $t")
          canceledException.addSuppressed(t)
          responseCallback.onFailure(this@RealCall, canceledException)
        }
        throw t
      } finally {
        client.dispatcher.finished(this)
      }
    }
  }
}

这里可以看到AsyncCall就是一个Runable对象,线程执行就会调用该对象的run方法,而executeOn方法就是执行runable对象. 在run方法中主要执行了以下几步:

  • 调用getResponseWithInterceptorChain()执行OkHttp拦截器,获取response对象
  • 调用responseCallback的onResponse方法将Response对象回调出去
  • 如果遇见IOException异常则调用responseCallback的onFailure方法将异常回调出去
  • 如果遇到其他异常,调用cancel()方法取消请求,调用responseCallback的onFailure方法将异常回调出去
  • 调用Dispatcher的finished方法结束执行

RealCall.getResponseWithInterceptorChain()

@Throws(IOException::class)
internal fun getResponseWithInterceptorChain(): Response {
  // 拦截器集合
  val interceptors = mutableListOf<Interceptor>()
  //添加用户自定义集合
  interceptors += client.interceptors
  interceptors += RetryAndFollowUpInterceptor(client)
  interceptors += BridgeInterceptor(client.cookieJar)
  interceptors += CacheInterceptor(client.cache)
  interceptors += ConnectInterceptor
  //如果不是sockect 添加newtwork拦截器
  if (!forWebSocket) {
    interceptors += client.networkInterceptors
  }
  interceptors += CallServerInterceptor(forWebSocket)
    //构建拦截器责任链
  val chain = RealInterceptorChain(
      call = this,
      interceptors = interceptors,
      index = 0,
      exchange = null,
      request = originalRequest,
      connectTimeoutMillis = client.connectTimeoutMillis,
      readTimeoutMillis = client.readTimeoutMillis,
      writeTimeoutMillis = client.writeTimeoutMillis
  )

  var calledNoMoreExchanges = false
  try {
     //执行拦截器责任链获取Response
    val response = chain.proceed(originalRequest)
    //如果取消了  则抛出异常
    if (isCanceled()) {
      response.closeQuietly()
      throw IOException("Canceled")
    }
    return response
  } catch (e: IOException) {
    calledNoMoreExchanges = true
    throw noMoreExchanges(e) as Throwable
  } finally {
    if (!calledNoMoreExchanges) {
      noMoreExchanges(null)
    }
  }
}

在这里主要执行了以下几步操作

  • 首先构建一个可变interceptor集合,将所有拦截器添加进去,这里如果是websocket则不添加networkInterceptor拦截器,这个interceptor集合的添加顺序也就是OkHttp拦截器的执行顺序
  • 构建一个RealInterceptorChain对象,将所有的拦截器包裹
  • 调用RealInterceptorChain的proceed的方法,获得Response对象

简单的总结一下:这里才用了责任链设计模式,构建RealInterceptorChain对象,然后执行proceed方法获取response对象

2.Interceptor

fun interface Interceptor {
    //拦截方法
  @Throws(IOException::class)
  fun intercept(chain: Chain): Response

  companion object {
    inline operator fun invoke(crossinline block: (chain: Chain) -> Response): Interceptor =
      Interceptor { block(it) }
  }

  interface Chain {
     //获取Request对象
    fun request(): Request

    //处理请求获取Reponse
    @Throws(IOException::class)
    fun proceed(request: Request): Response

    ......
  }
}
class RealInterceptorChain(
  internal val call: RealCall,
  private val interceptors: List<Interceptor>,
  private val index: Int,
  internal val exchange: Exchange?,
  internal val request: Request,
  internal val connectTimeoutMillis: Int,
  internal val readTimeoutMillis: Int,
  internal val writeTimeoutMillis: Int
) : Interceptor.Chain {


  internal fun copy(
    index: Int = this.index,
    exchange: Exchange? = this.exchange,
    request: Request = this.request,
    connectTimeoutMillis: Int = this.connectTimeoutMillis,
    readTimeoutMillis: Int = this.readTimeoutMillis,
    writeTimeoutMillis: Int = this.writeTimeoutMillis
  ) = RealInterceptorChain(call, interceptors, index, exchange, request, connectTimeoutMillis,
      readTimeoutMillis, writeTimeoutMillis)
  
      ......
      
  override fun call(): Call = call

  override fun request(): Request = request

  @Throws(IOException::class)
  override fun proceed(request: Request): Response {
    check(index < interceptors.size)

     ......

    val next = copy(index = index + 1, request = request)
    val interceptor = interceptors[index]

    @Suppress("USELESS_ELVIS")
    val response = interceptor.intercept(next) ?: throw NullPointerException(
        "interceptor $interceptor returned null")

     ......

    return response
  }
}

这里看一看到copy()方法就是创建了一个RealInterceptorChain()对象,不过需要注意的是index在创建对象时是index = index + 1,这样就会执行index对应下标的拦截器,不断的调用下一个拦截器,直到有response对象返回,也就是chain.proceed(originalRequest)结束。

RetryAndFollowUpInterceptor(错误重定向拦截器)

主要处理了如下几个方向的问题:

  • 1.异常,或者协议重试(408客户端超时,权限问题,503服务暂时不处理,retry-after为0)
  • 2.重定向
  • 3.重试的次数不能超过20次。

RetryAndFollowUpInterceptor.intercept()

@Throws(IOException::class)
override fun intercept(chain: Interceptor.Chain): Response {
val realChain = chain as RealInterceptorChain
var request = chain.request
val call = realChain.call
var followUpCount = 0
var priorResponse: Response? = null
var newExchangeFinder = true
var recoveredFailures = listOf<IOException>()
while (true) {
  //这里会新建一个ExchangeFinder,ConnectInterceptor会使用到
  call.enterNetworkInterceptorExchange(request, newExchangeFinder)

  var response: Response
  var closeActiveExchange = true
  try {
    if (call.isCanceled()) {
      throw IOException("Canceled")
    }

    try {
      response = realChain.proceed(request)
      newExchangeFinder = true
    } catch (e: RouteException) {
      //尝试通过路由连接失败。该请求将不会被发送。
      if (!recover(e.lastConnectException, call, request, requestSendStarted = false)) {
        throw e.firstConnectException.withSuppressed(recoveredFailures)
      } else {
        recoveredFailures += e.firstConnectException
      }
      newExchangeFinder = false
      continue
    } catch (e: IOException) {
      //尝试与服务器通信失败。该请求可能已发送。
      if (!recover(e, call, request, requestSendStarted = e !is ConnectionShutdownException)) {
        throw e.withSuppressed(recoveredFailures)
      } else {
        recoveredFailures += e
      }
      newExchangeFinder = false
      continue
    }

   //尝试关联上一个response,注意:body是为null
    if (priorResponse != null) {
      response = response.newBuilder()
          .priorResponse(priorResponse.newBuilder()
              .body(null)
              .build())
          .build()
    }

    val exchange = call.interceptorScopedExchange
    //会根据 responseCode 来判断,构建一个新的request并返回来重试或者重定向
    val followUp = followUpRequest(response, exchange)

    if (followUp == null) {
      if (exchange != null && exchange.isDuplex) {
        call.timeoutEarlyExit()
      }
      closeActiveExchange = false
      return response
    }
    //如果请求体是一次性的,不需要再次重试
    val followUpBody = followUp.body
    if (followUpBody != null && followUpBody.isOneShot()) {
      closeActiveExchange = false
      return response
    }

    response.body?.closeQuietly()
    //最大重试次数,不同的浏览器是不同的,比如:Chrome为21,Safari则是16
    if (++followUpCount > MAX_FOLLOW_UPS) {
        throw ProtocolException("Too many follow-up requests: $followUpCount")
    }


    request = followUp
    priorResponse = response
  } finally {
    call.exitNetworkInterceptorExchange(closeActiveExchange)
  }
}
}
  • 1.调用RealCall的enterNetworkInterceptorExchange方法实例化一个ExchangeFinder在RealCall对象中。

  • 2.执行RealCall的proceed 方法,进入下一个拦截器,进行下一步的请求处理。

  • 3.如果出现路由异常,则通过recover方法校验,当前的连接是否可以重试,不能重试则抛出异常,离开当前的循环。

private fun recover(
  e: IOException,
  call: RealCall,
  userRequest: Request,
  requestSendStarted: Boolean
): Boolean {
  //禁止重连
  if (!client.retryOnConnectionFailure) return false

  // 不能再次发送请求体
  if (requestSendStarted && requestIsOneShot(e, userRequest)) return false

  // 致命异常
  if (!isRecoverable(e, requestSendStarted)) return false

  // 没有更多线路可以重连
  if (!call.retryAfterFailure()) return false

  // 对于故障恢复,将相同的路由选择器与新连接一起使用
  return true
}

BridgeInterceptor(应用层和网络层的桥接拦截器)

主要处理了如下几个问题:

  • 主要将Content-Type、Content-Length、Host等一些数据添加到头部。
  • 拿到数据之后对数据进行处理,判断是否为gzip,进行对数据数据解压。

BridgeInterceptor.intercept()

@Throws(IOException::class)
override fun intercept(chain: Interceptor.Chain): Response {
  //获取原始请求数据
  val userRequest = chain.request()
  val requestBuilder = userRequest.newBuilder()
   //重新构建请求 添加一些必要的请求头信息
  val body = userRequest.body
  if (body != null) {
    val contentType = body.contentType()
    if (contentType != null) {
      requestBuilder.header("Content-Type", contentType.toString())
    }

    val contentLength = body.contentLength()
    if (contentLength != -1L) {
      requestBuilder.header("Content-Length", contentLength.toString())
      requestBuilder.removeHeader("Transfer-Encoding")
    } else {
      requestBuilder.header("Transfer-Encoding", "chunked")
      requestBuilder.removeHeader("Content-Length")
    }
  }

  if (userRequest.header("Host") == null) {
    requestBuilder.header("Host", userRequest.url.toHostHeader())
  }

  if (userRequest.header("Connection") == null) {
    requestBuilder.header("Connection", "Keep-Alive")
  }

  var transparentGzip = false
  if (userRequest.header("Accept-Encoding") == null && userRequest.header("Range") == null) {
    transparentGzip = true
    requestBuilder.header("Accept-Encoding", "gzip")
  }

  val cookies = cookieJar.loadForRequest(userRequest.url)
  if (cookies.isNotEmpty()) {
    requestBuilder.header("Cookie", cookieHeader(cookies))
  }

  if (userRequest.header("User-Agent") == null) {
    requestBuilder.header("User-Agent", userAgent)
  }
    //执行下一个拦截器
  val networkResponse = chain.proceed(requestBuilder.build())

  cookieJar.receiveHeaders(userRequest.url, networkResponse.headers)
  //创建一个新的responseBuilder,目的是将原始请求数据构建到response中
  val responseBuilder = networkResponse.newBuilder()
      .request(userRequest)

  if (transparentGzip &&
      "gzip".equals(networkResponse.header("Content-Encoding"), ignoreCase = true) &&
      networkResponse.promisesBody()) {
    val responseBody = networkResponse.body
    if (responseBody != null) {
      val gzipSource = GzipSource(responseBody.source())
      val strippedHeaders = networkResponse.headers.newBuilder()
          .removeAll("Content-Encoding")
          .removeAll("Content-Length")
          .build()
         
       //修改response header信息,移除Content-Encoding,Content-Length信息
      responseBuilder.headers(strippedHeaders)
      val contentType = networkResponse.header("Content-Type"
     //修改response body信息
      responseBuilder.body(RealResponseBody(contentType, -1L, gzipSource.buffer()))
    }
  }

  return responseBuilder.build()
}
  • 设置头部的Content-Type.说明内容类型是什么
  • 如果contentLength大于等于0,则设置头部的Content-Length(说明内容大小是多少);否则设置头部的Transfer-Encoding为chunked(说明传输编码为分块传输)
  • 如果Host不存在,设置头部的Host(在Http 1.1之后出现,可以通过同一个URL访问到不同主机,从而实现服务器虚拟服务器的负载均衡。如果1.1之后不设置就会返回404)。
  • 如果Connection不存在,设置头部的Connection为Keep-Alive(代表连接状态需要保持活跃)
  • 如果Accept-Encoding且Range为空,则强制设置Accept-Encoding为gzip(说明请求将会以gzip方式压缩)
  • 从CookieJar的缓存中取出cookie设置到头部的Cookie
  • 如果User-Agent为空,则设置User-Agent到头部

CacheInterceptor(缓存拦截器)

用户通过OkHttpClient.cache来配置缓存,缓存拦截器通过CacheStrategy来判断是使用网络还是缓存来构建response

CacheInterceptor.intercept()

@Throws(IOException::class)
override fun intercept(chain: Interceptor.Chain): Response {
  val call = chain.call()
  //通过request从OkHttpClient.cache中获取缓存
  val cacheCandidate = cache?.get(chain.request())

  val now = System.currentTimeMillis()
 //创建缓存策略
  val strategy = CacheStrategy.Factory(now, chain.request(), cacheCandidate).compute()
    //为空表示不使用网络,反之,则表示使用网络
    val networkRequest = strategy.networkRequest
    //为空表示不使用缓存,反之,则表示使用缓存
    val cacheResponse = strategy.cacheResponse
    //追踪网络与缓存的使用情况
    cache?.trackResponse(strategy)
    val listener = (call as? RealCall)?.eventListener ?: EventListener.NONE
    //有缓存但不适用,关闭它
    if (cacheCandidate != null && cacheResponse == null) {
      cacheCandidate.body?.closeQuietly()
    }


 
    //如果网络被禁止,但是缓存又是空的,构建一个code为504的response,并返回
  if (networkRequest == null && cacheResponse == null) {
    return Response.Builder()
        .request(chain.request())
        .protocol(Protocol.HTTP_1_1)
        .code(HTTP_GATEWAY_TIMEOUT)
        .message("Unsatisfiable Request (only-if-cached)")
        .body(EMPTY_RESPONSE)
        .sentRequestAtMillis(-1L)
        .receivedResponseAtMillis(System.currentTimeMillis())
        .build().also {
          listener.satisfactionFailure(call, it)
        }
  }

 //如果我们禁用了网络不使用网络,且有缓存,直接根据缓存内容构建并返回response
  if (networkRequest == null) {
    return cacheResponse!!.newBuilder()
        .cacheResponse(stripBody(cacheResponse))
        .build().also {
          listener.cacheHit(call, it)
        }
  }

   //为缓存添加监听
  if (cacheResponse != null) {
    listener.cacheConditionalHit(call, cacheResponse)
  } else if (cache != null) {
    listener.cacheMiss(call)
  }

  var networkResponse: Response? = null
  try {
      //执行下一个拦截器
    networkResponse = chain.proceed(networkRequest)
  } finally {
    //捕获I/O或其他异常,请求失败,networkResponse为空,且有缓存的时候,不暴露缓存内容
    if (networkResponse == null && cacheCandidate != null) {
       //否则关闭缓存响应体
      cacheCandidate.body?.closeQuietly()
    }
  }

    //如果有缓存
  if (cacheResponse != null) {
    //且网络返回response code为304的时候,使用缓存内容新构建一个Response返回。
    if (networkResponse?.code == HTTP_NOT_MODIFIED) {
      val response = cacheResponse.newBuilder()
          .headers(combine(cacheResponse.headers, networkResponse.headers))
          .sentRequestAtMillis(networkResponse.sentRequestAtMillis)
          .receivedResponseAtMillis(networkResponse.receivedResponseAtMillis)
          .cacheResponse(stripBody(cacheResponse))
          .networkResponse(stripBody(networkResponse))
          .build()

      networkResponse.body!!.close()
      cache!!.trackConditionalCacheHit()
      cache.update(cacheResponse, response)
      return response.also {
        listener.cacheHit(call, it)
      }
    } else {
    //否则关闭缓存响应体
      cacheResponse.body?.closeQuietly()
    }
  }

  //构建网络请求的response
  val response = networkResponse!!.newBuilder()
      .cacheResponse(stripBody(cacheResponse))
      .networkResponse(stripBody(networkResponse))
      .build()

    //如果cache不为null,即用户在OkHttpClient中配置了缓存,则将上一步新构建的网络请求response存到cache中
  if (cache != null) {
    //根据response的code,header以及CacheControl.noStore来判断是否可以缓存
    if (response.promisesBody() && CacheStrategy.isCacheable(response, networkRequest)) {
     // 将该response存入缓存
      val cacheRequest = cache.put(response)
      return cacheWritingResponse(cacheRequest, response).also {
        if (cacheResponse != null) {
          listener.cacheMiss(call)
        }
      }
    }
    
    //根据请求方法来判断缓存是否有效,只对Get请求进行缓存,其它方法的请求则移除
    if (HttpMethod.invalidatesCache(networkRequest.method)) {
      try {
         //缓存无效,将该请求缓存从client缓存配置中移除
        cache.remove(networkRequest)
      } catch (_: IOException) {
       
      }
    }
  }

  return response
}

网络请求前:

  • 首先根据request从OkHttpClient.cache中获取缓存,通过CacheStrategy获取本次请求的请求体及缓存的响应体。
  • 如果 请求体networkRequest和响应体cacheResponse都为空的话,则返回错误码为 504
  • 如果 请求体networkRequest为空 响应体cacheResponse不为空的话,则将该响应体返回
  • 如果请求体networkRequest不为空的话,则进入下一个拦截器。

网络请求后:

  • 如果当前cacheResponse不为空,且 networkResponse状态码为304, 则代表数据没有变化,那么就会根据 cacheResponse 构建一个新的 response,根据当前时间更新到缓存当中,并返回到上一拦截器中
  • 如果networkResponse状态码不为304,则判断是否进行缓存,最后返回到上一拦截器中

从LruCache中获取缓存

val cacheCandidate = cache?.get(chain.request())
internal fun get(request: Request): Response? {
  val key = key(request.url)
  val snapshot: DiskLruCache.Snapshot = try {
    cache[key] ?: return null
  } catch (_: IOException) {
    return null // Give up because the cache cannot be read.
  }

  val entry: Entry = try {
    Entry(snapshot.getSource(ENTRY_METADATA))
  } catch (_: IOException) {
    snapshot.closeQuietly()
    return null
  }

  val response = entry.response(snapshot)
  if (!entry.matches(request, response)) {
    response.body?.closeQuietly()
    return null
  }

  return response
}

@JvmStatic
fun key(url: HttpUrl): String = url.toString().encodeUtf8().md5().hex()
  • 首先将url转化为urf-8,并且通过md5拿到摘要,再调用hex获取16进制的字符串,该字符串就是LruCache的key;
  • 通过key获取到DiskLruCache.Snapshot对象(这里在DiskLruCache中重写了get方法),根据DiskLruCache.Snapshot对象获取到okio 的source。

DiskLruCache:

@Synchronized @Throws(IOException::class)
operator fun get(key: String): Snapshot? {
  initialize()

  checkNotClosed()
  validateKey(key)
  val entry = lruEntries[key] ?: return null
  val snapshot = entry.snapshot() ?: return null

  redundantOpCount++
  journalWriter!!.writeUtf8(READ)
      .writeByte(' '.toInt())
      .writeUtf8(key)
      .writeByte('\n'.toInt())
  if (journalRebuildRequired()) {
    cleanupQueue.schedule(cleanupTask)
  }

  return snapshot
}

ConnectInterceptot(链接拦截器)

object ConnectInterceptor : Interceptor {
  @Throws(IOException::class)
  override fun intercept(chain: Interceptor.Chain): Response {
    val realChain = chain as RealInterceptorChain
    val exchange = realChain.call.initExchange(chain)
    val connectedChain = realChain.copy(exchange = exchange)
    return connectedChain.proceed(realChain.request)
  }
}
  • 首先初始化一个可交换连接的对象
  • 拷贝一个全新的RealInterceptorChain对象,并且调用该对象的proceed方法执行下一拦截器

这个拦截器主要操作都在initExchange(chain)当中

initExchange()

internal fun initExchange(chain: RealInterceptorChain): Exchange {
  synchronized(this) {
    check(expectMoreExchanges) { "released" }
    check(!responseBodyOpen)
    check(!requestBodyOpen)
  }

  val exchangeFinder = this.exchangeFinder!!
  val codec = exchangeFinder.find(client, chain)
  val result = Exchange(this, eventListener, exchangeFinder, codec)
  this.interceptorScopedExchange = result
  this.exchange = result
  synchronized(this) {
    this.requestBodyOpen = true
    this.responseBodyOpen = true
  }

  if (canceled) throw IOException("Canceled")
  return result
}

exchangeFinder

fun find(
  client: OkHttpClient,
  chain: RealInterceptorChain
): ExchangeCodec {
  try {
    val resultConnection = findHealthyConnection(
        connectTimeout = chain.connectTimeoutMillis,
        readTimeout = chain.readTimeoutMillis,
        writeTimeout = chain.writeTimeoutMillis,
        pingIntervalMillis = client.pingIntervalMillis,
        connectionRetryEnabled = client.retryOnConnectionFailure,
        doExtensiveHealthChecks = chain.request.method != "GET"
    )
    return resultConnection.newCodec(client, chain)
  } catch (e: RouteException) {
    trackFailure(e.lastConnectException)
    throw e
  } catch (e: IOException) {
    trackFailure(e)
    throw RouteException(e)
  }
}
  • 通过findHealthyConnection找到一个健康的连接resultConnection,也就是一个活跃的连接,
  • 调用 resultConnection.newCodec(client, chain)获取到ExchangeCodec进行返回

findHealthyConnection

@Throws(IOException::class)
private fun findHealthyConnection(
  connectTimeout: Int,
  readTimeout: Int,
  writeTimeout: Int,
  pingIntervalMillis: Int,
  connectionRetryEnabled: Boolean,
  doExtensiveHealthChecks: Boolean
): RealConnection {
  while (true) {
    val candidate = findConnection(
        connectTimeout = connectTimeout,
        readTimeout = readTimeout,
        writeTimeout = writeTimeout,
        pingIntervalMillis = pingIntervalMillis,
        connectionRetryEnabled = connectionRetryEnabled
    )

    if (candidate.isHealthy(doExtensiveHealthChecks)) {
      return candidate
    }
    candidate.noNewExchanges()
    if (nextRouteToTry != null) continue
    val routesLeft = routeSelection?.hasNext() ?: true
    if (routesLeft) continue
    val routesSelectionLeft = routeSelector?.hasNext() ?: true
    if (routesSelectionLeft) continue
    throw IOException("exhausted all routes")
  }
}
  • findConnection从OkHttp的连接池中找到对应的RealConnection进行返回,如果没有的话,则创建一个
  • candidate.isHealthy(doExtensiveHealthChecks)检查该连接是否活跃可用
  • 如果当前连接是不健康,则调用candidate.noNewExchanges()noNewExchanges设置为true,表示该连接存在问题
  • if (routesSelectionLeft) continue判断是否还有其他路由需要尝试,如果有的话则返回true,进入下一循环。

findConnection()

@Throws(IOException::class)
private fun findConnection(
  connectTimeout: Int,
  readTimeout: Int,
  writeTimeout: Int,
  pingIntervalMillis: Int,
  connectionRetryEnabled: Boolean
): RealConnection {
  if (call.isCanceled()) throw IOException("Canceled")
  val callConnection = call.connection 
  if (callConnection != null) {
    var toClose: Socket? = null
    synchronized(callConnection) {
      if (callConnection.noNewExchanges || !sameHostAndPort(callConnection.route().address.url)) {
        toClose = call.releaseConnectionNoEvents()
      }
    }

    if (call.connection != null) {
      check(toClose == null)
      return callConnection
    }

    toClose?.closeQuietly()
    eventListener.connectionReleased(call, callConnection)
  }

  refusedStreamCount = 0
  connectionShutdownCount = 0
  otherFailureCount = 0

  if (connectionPool.callAcquirePooledConnection(address, call, null, false)) {
    val result = call.connection!!
    eventListener.connectionAcquired(call, result)
    return result
  }

  val routes: List<Route>?
  val route: Route
  if (nextRouteToTry != null) {
    routes = null
    route = nextRouteToTry!!
    nextRouteToTry = null
  } else if (routeSelection != null && routeSelection!!.hasNext()) {
    routes = null
    route = routeSelection!!.next()
  } else {
    var localRouteSelector = routeSelector
    if (localRouteSelector == null) {
      localRouteSelector = RouteSelector(address, call.client.routeDatabase, call, eventListener)
      this.routeSelector = localRouteSelector
    }
    val localRouteSelection = localRouteSelector.next()
    routeSelection = localRouteSelection
    routes = localRouteSelection.routes

    if (call.isCanceled()) throw IOException("Canceled")

    if (connectionPool.callAcquirePooledConnection(address, call, routes, false)) {
      val result = call.connection!!
      eventListener.connectionAcquired(call, result)
      return result
    }

    route = localRouteSelection.next()
  }

  val newConnection = RealConnection(connectionPool, route)
  call.connectionToCancel = newConnection
  try {
    newConnection.connect(
        connectTimeout,
        readTimeout,
        writeTimeout,
        pingIntervalMillis,
        connectionRetryEnabled,
        call,
        eventListener
    )
  } finally {
    call.connectionToCancel = null
  }
  call.client.routeDatabase.connected(newConnection.route())

  if (connectionPool.callAcquirePooledConnection(address, call, routes, true)) {
    val result = call.connection!!
    nextRouteToTry = route
    newConnection.socket().closeQuietly()
    eventListener.connectionAcquired(call, result)
    return result
  }

  synchronized(newConnection) {
    connectionPool.put(newConnection)
    call.acquireConnectionNoEvents(newConnection)
  }

  eventListener.connectionAcquired(call, newConnection)
  return newConnection
}
  • call.connection首先从RealCall对象中获取 RealConnection

  • 在获取到RealConnection对象时,存在三种情况

    1. RealConnection对象不为空,但是host和port不匹配
    2. RealConnection对象不为空,完全匹配
    3. RealConnection对象为空
  • 判断RealConnection对象是否为空, 如果不为空则检查一下host和port是否匹配。

    • 如果不匹配则调用releaseConnectionNoEvents(),把RealConnection绑定的RealCall队列中对应的RealCall移除,并从ConnectionPool中移除该RealConnection,当前RealCall中绑定的RealConnection设置为空, 并获取当前缓存RealConnectionsocket对象,并关闭该socket
    • 如果noNewExchangesfalse,并且hostport匹配,则返回该callConnection对象
    • 如果RealConnection对象为空,则会通过connectionPoolroute生成一个新的RealConnection对象

.......省略。。。

NetWorkInterceptor(网络连接器)

CallServerInterceptor(请求拦截器)

@Throws(IOException::class)
override fun intercept(chain: Interceptor.Chain): Response {
  val realChain = chain as RealInterceptorChain
  val exchange = realChain.exchange!!
  val request = realChain.request
  val requestBody = request.body
  val sentRequestMillis = System.currentTimeMillis()

  exchange.writeRequestHeaders(request)

  var invokeStartEvent = true
  var responseBuilder: Response.Builder? = null
  if (HttpMethod.permitsRequestBody(request.method) && requestBody != null) {
    if ("100-continue".equals(request.header("Expect"), ignoreCase = true)) {
      exchange.flushRequest()
      responseBuilder = exchange.readResponseHeaders(expectContinue = true)
      exchange.responseHeadersStart()
      invokeStartEvent = false
    }
    if (responseBuilder == null) {
      if (requestBody.isDuplex()) {
        exchange.flushRequest()
        val bufferedRequestBody = exchange.createRequestBody(request, true).buffer()
        requestBody.writeTo(bufferedRequestBody)
      } else {
        val bufferedRequestBody = exchange.createRequestBody(request, false).buffer()
        requestBody.writeTo(bufferedRequestBody)
        bufferedRequestBody.close()
      }
    } else {
      exchange.noRequestBody()
      if (!exchange.connection.isMultiplexed) {
        exchange.noNewExchangesOnConnection()
      }
    }
  } else {
    exchange.noRequestBody()
  }

  if (requestBody == null || !requestBody.isDuplex()) {
    exchange.finishRequest()
  }
  if (responseBuilder == null) {
    responseBuilder = exchange.readResponseHeaders(expectContinue = false)!!
    if (invokeStartEvent) {
      exchange.responseHeadersStart()
      invokeStartEvent = false
    }
  }
  var response = responseBuilder
      .request(request)
      .handshake(exchange.connection.handshake())
      .sentRequestAtMillis(sentRequestMillis)
      .receivedResponseAtMillis(System.currentTimeMillis())
      .build()
  var code = response.code
  if (code == 100) {
    responseBuilder = exchange.readResponseHeaders(expectContinue = false)!!
    if (invokeStartEvent) {
      exchange.responseHeadersStart()
    }
    response = responseBuilder
        .request(request)
        .handshake(exchange.connection.handshake())
        .sentRequestAtMillis(sentRequestMillis)
        .receivedResponseAtMillis(System.currentTimeMillis())
        .build()
    code = response.code
  }

  exchange.responseHeadersEnd(response)

  response = if (forWebSocket && code == 101) {
    response.newBuilder()
        .body(EMPTY_RESPONSE)
        .build()
  } else {
    response.newBuilder()
        .body(exchange.openResponseBody(response))
        .build()
  }
  if ("close".equals(response.request.header("Connection"), ignoreCase = true) ||
      "close".equals(response.header("Connection"), ignoreCase = true)) {
    exchange.noNewExchangesOnConnection()
  }
  if ((code == 204 || code == 205) && response.body?.contentLength() ?: -1L > 0L) {
    throw ProtocolException(
        "HTTP $code had non-zero Content-Length: ${response.body?.contentLength()}")
  }
  return response
}
  • exchange.writeRequestHeaders(request)写入请求头信息
  • 判断请求方式是不是GETHEAD,如果不是则需要传入请求体,接着判断请求头中的Expect值是否为100-continue,如果是的话,则会读取响应体的头部信息,如果读出的Response.Builder为空,接着判断 requestBody.isDuplex(),如果为true的话,则刷新缓冲区,通过exchange.createRequestBody(request, true).buffer()创建bufferedRequestBody,往请求的requestBody写入数据,如果为false的话,,通过exchange.createRequestBody(request, true).buffer()创建bufferedRequestBody,写入输出流中发送数据。
  • 如果请求方式是GETHEAD的话,则没有请求体。
  • 如果requestBody为空,也就是没有请求体,或者requestBody.isDuplex()为false的话,则结束请求。
  • 如果responseBuilder为空的话,则调用exchange.readResponseHeaders方法
  • 获取响应体
  • 判断响应体的code是否为100,如果响应体为100 则是说后面还有数据需要传输,则会重新调用 exchange.readResponseHeaders方法,再次生成响应体
  • 判断code是否为101 并且 为websocekt请求,如果是的话,则生成一个空的response,否则就会通过exchange.openResponseBody(response)读取response中的数据生成一个响应体。
  • 最后判断code是否为204、205并且响应体的body为空的话则抛出异常,否则正常返回

。。。。。。。省略

参考:

Overview - OkHttp

OkHttp-源码分析(一) - 掘金

OkHttp-源码分析(二) - 掘金

OkHttp-源码分析(三) - 掘金

OKHTTP 源码分析(1)调用流程梳理_okhttpclient().newbuilder().build();-CSDN博客

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1100770.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

8.14 PowerBI系列之DAX函数专题-分析客户购买行为

需求 实现 其实如果同时输出订单号的情况下&#xff0c;可以通过订单号出现的次数判断同一订单中同时购买与否的关系。 同时购买了A和B的客户 var v_cust_1 calculatetable(values(客户表[客户姓名]),filter(订单表,订单表[产品编号] "off-pa-10001970")) var v…

2016款奔驰C200车COMAND显示屏黑屏

作者&#xff1a;中鑫之宝鹤壁店 赵玉宾 赵玉宾&#xff0c;从事汽车维修工作9年&#xff0c;现任中鑫之宝汽车服务有限公司鹤壁分公司高级维修技师。 故障现象 一辆2016款奔驰C200车&#xff0c;搭载274发动机&#xff0c;累计行驶里程约为7万km。车主反映&#xff0c;车辆行…

亚马逊、eBay,速卖通,国际站买家账号支付异常问题解决方法

如何解决下单被砍、封号问题&#xff0c;建议采取以下措施&#xff1a; 买家账号下单&#xff0c;不单纯只是解决支付卡、IP问题就可以了&#xff0c;因为平台大数据风控点很多&#xff0c; 我们防关联具体要解决几个问题 一&#xff1a;要硬件参数的关联、安全码、地区码、…

【定时开关机】windows 10 如何设置定时开关机

一、需求 二、场景 三、思路 四、实现 A. 设置来电开机 B. 设置及定时关机 一、需求 需要一台 win 10 的电脑在工作时间内自动开关机&#xff08;早 8:30 - 晚&#xff1a;6:05&#xff09; 二、场景 开机&#xff1a;早 8:30 关机&#xff1a;晚 6:05 三、思路 【开机…

github 终端克隆操作,以及对 https/ssh 的理解

前言 最近瞎搞 github 的一些配置&#xff0c;结果搞得有一段时间克隆不了仓库。不过经历了这次风波后&#xff0c;我对 github 的一些原理有了更清楚的了解。所以想稍微写一小篇文章总结输出一下&#xff0c;也欢迎有疑问的读者与博主进一步交流&#xff0c;我的理解还是有限…

2023年中国钢卷尺产量、销量、市场均价及市场规模分析[图]

卷尺是日常生活中常用的工量具&#xff0c;是家庭必备工具之一。鲁班尺、风水尺、文公尺同样属于钢卷尺。钢卷尺是建筑和装修常用工具。钢卷尺可分为&#xff0c;自卷式卷尺、制动式卷尺、摇卷式卷尺。钢卷尺的其他名称有&#xff1a;钢皮卷尺、钢盒尺。 钢卷尺市场已经告别了以…

什么是库存管理?无需Excel,2023年这几款大热库存管理软件你get了吗?

什么是库存管理&#xff1f;库存管理是什么意思&#xff1f;都有哪些好用的库存管理系统&#xff1f;相信这些都是大家非常关注的话题&#xff0c;这篇就跟大家详细唠唠什么是库存管理&#xff0c;都用什么系统可以进行库存管理&#xff0c;并且为大家盘点2023年这几款大热库存…

和硕首次参加展OCP 峰会,将发布多项AI合作项目产品 | 百能云芯

电子代工大厂和硕联合科技宣布&#xff0c;将参与今年的 OCP 全球峰会 (OCP Global Summit)&#xff0c;展示与英伟达 (NVIDIA) 合作成果&#xff0c;包含使用英伟达 GH200 Grace Hopper 超级芯片的 MGX AI 服务器&#xff0c;以及搭载 A100、L40 等服务器产品。 OCP 峰会于 10…

斯坦福JSKarel编程机器人使用介绍

斯坦福JSKarel编程机器人使用介绍 为了避免被编程语言固有的复杂性所困扰&#xff0c;有一个被称为卡雷尔&#xff08;Karel&#xff09;机器人的微型世界&#xff08;microworld&#xff09;的简化环境&#xff0c;可以让编程初学者从中学习理解编程的基本概念&#xff0c;而…

GaussDB for openGauss部署形态

前言 华为云数据库GaussDB是华为自主创新研发的分布式关系型数据库&#xff0c;具有高性能、高可用、高安全、低成本的特点&#xff0c;本文带你详细了解GaussDB数据库的部署形态。 1、GaussDB部署形态三种类型 GaussDB部署形态&#xff1a;单机 独立部署是将数据库组件部署…

10.17课上(七段显示器,递归异或与电路)

异或的递归与数电实现 用二选一选择器实现异或函数 在异或当中&#xff0c;如果有一项为0&#xff0c;就可以把那一项消掉&#xff1b;如果有一项为1&#xff0c;就是把剩下的所有项运算完的结果取反 &#xff08;由此在算法当中可以采用递归解决&#xff09; 当w1为0时&…

电脑蓝牙与ESP32蓝牙连接,让电脑发现ESP32

win11蓝牙默认只查看常见蓝牙设备。ESP32创建的蓝牙很有可能是看不到的。 再蓝牙设备发现一栏选择高级&#xff0c;才能查看所有蓝牙设备。 只要下面几行代码&#xff0c;就能让PC发现ESP32 #include <BLEDevice.h> // 引入相关库void setup() {BLEDevice::init("…

使用 PDB Alignment Tool 对 PDB 中多个蛋白结构进行比对

0. 说明&#xff1a; 利用 PDB 提供的在线工具 PDB Alignment Tool (https://www.rcsb.org/alignment) 对 PDB 中多个蛋白进行结构比对&#xff0c;并将比对结果输出&#xff0c;用于后续计算不同链上氨基酸之间的距离。 1. 步骤&#xff08;以 3GBM_A, 3FKU_A 和 2FK0_A 为例…

Linux学习——进程状态

目录 一&#xff0c;进程状态 1&#xff0c;进程状态的分类 2.状态的本质 3.进程状态详解 1.运行状态 2.阻塞状态 3.挂起状态 4.Linux内核中的状态分类 一&#xff0c;进程状态 1&#xff0c;进程状态的分类 如下图&#xff1a; 在计算机中我们的状态的分类便如下图所示…

16-k8s-configMap配置管理中心

文章目录 一、相关概念二、基于目录创建configMap三、基于文件创建configMap四、基于自定义参数创建configMap五、configMap使用六、configMap热更新 一、相关概念 简介 为了解决传统容器中配置的挂载、变更、管理等问题&#xff0c;在k8s中引入了一个叫做configmap的资源对象&…

采用医疗AI、自然语言处理技术的java智能导诊导医系统源码

一套java智能导诊导医系统源码&#xff08;演示自主版权商业项目应用&#xff09; 随着人工智能技术的快速发展&#xff0c;语音识别与自然语言理解技术的成熟应用&#xff0c;基于人工智能的智能导诊导医逐渐出现在患者的生活视角中&#xff0c;智能导诊系统应用到医院就医场景…

同为科技TOWE智能PDU引领数据中心机房远控用电安全高效

随着数据中心的环境变得更加动态和复杂&#xff0c;许多数据中心都在对数据中心管理人员施加压力&#xff0c;要求提高可用性&#xff0c;同时降低成本&#xff0c;提升效率。新一代高密度服务器和网络设备的投入使用&#xff0c;增加了对更高密度机架的需求&#xff0c;并对整…

《持续交付:发布可靠软件的系统方法》- 读书笔记(五)

持续交付&#xff1a;发布可靠软件的系统方法&#xff08;五&#xff09; 第二部分——部署流水线第 5 章 部署流水线解析5.1 引言5.2 什么是部署流水线5.3 部署流水线的相关实践5.3.1 只生成一次二进制包5.3.2 对不同环境采用同一部署方式5.3.3 对部署进行冒烟测试5.3.4 向生产…

vcpkg manifest 的使用

最近项目上要使用 CMakeLists 管理&#xff0c;由于 Windows 版本有依赖到 vcpkg 提供的库&#xff0c;所以需要使用 vcpkg manifest 来统一设置库的版本&#xff0c;方便后续维护 推荐一个文章&#xff0c;介绍的可以说是非常全面了 VCPKG 特性 - Versioning 不过里面也有一些…

『C++ - STL』之优先级队列( priority_queue )

文章目录 前言优先级队列的结构优先级队列的模拟实现仿函数 最终代码 前言 什么是优先级队列&#xff0c;从该名中可以知道他一定有队列的一定属性&#xff0c;即先入先出(LILO)&#xff0c;而这里的优先级则可以判断出它的另一个特点就是可以按照一定的条件将符合该条件的先进…