简介

okhttp是Android中应用最广的http网络请求框架。结构优雅,性能强大。我们通过阅读它,对网络库的架构进行学习。本篇主要阅读okhttp任务队列的结构,了解okhttp的任务调度。

基本结构

网络请求是一个典型的生产/消费模型。我们的每一个请求都会加入一个缓冲队列,然后在合适的时候进行消费。

我们以异步请求为例:

okhttp——任务模型 - 图1

OKHttpClient提供方法生产Call,Dispatcher负责管理、分发和执行AsyncCall。

下面,我们来细致地看一下代码。

详细代码

基本调用

还是以异步任务为例,一次典型的okhttp的调用:

  1. String url = "http://wwww.baidu.com";
  2. OkHttpClient okHttpClient = new OkHttpClient();
  3. final Request request = new Request.Builder()
  4. .url(url)
  5. .get()//默认就是GET请求,可以不写
  6. .build();
  7. Call call = okHttpClient.newCall(request);
  8. call.enqueue(new Callback() {
  9. @Override
  10. public void onFailure(Call call, IOException e) {
  11. Log.d(TAG, "onFailure: ");
  12. }
  13. @Override
  14. public void onResponse(Call call, Response response) throws IOException {
  15. Log.d(TAG, "onResponse: " + response.body().string());
  16. }
  17. });

我们可以看到,这个过程大致分为两部,生成一个新的call,将call加入队列。

Request

Request是okhttp中的http请求封装类,它管理了http协议中的参数,如Header,RequestBody等

  1. class Request internal constructor(
  2. internal val url: HttpUrl,
  3. builder: Builder
  4. ) {
  5. internal val method: String = builder.method
  6. internal val headers: Headers = builder.headers.build()
  7. internal val body: RequestBody? = builder.body
  8. internal val tags: Map<Class<*>, Any> = Util.immutableMap(builder.tags)
  9. ......
  10. }

OKHttpClient

OKHttpClient是okhttp中总管类,管理了okhttp几乎所有抽象模块和各种配置。

  1. open class OkHttpClient internal constructor(
  2. builder: Builder
  3. ) : Cloneable, Call.Factory, WebSocket.Factory {
  4. private val dispatcher: Dispatcher = builder.dispatcher
  5. private val proxy: Proxy? = builder.proxy
  6. private val protocols: List<Protocol> = builder.protocols
  7. private val connectionSpecs: List<ConnectionSpec> = builder.connectionSpecs
  8. private val interceptors: List<Interceptor> =
  9. Util.immutableList(builder.interceptors)
  10. private val networkInterceptors: List<Interceptor> =
  11. Util.immutableList(builder.networkInterceptors)
  12. private val eventListenerFactory: EventListener.Factory = builder.eventListenerFactory
  13. private val proxySelector: ProxySelector = builder.proxySelector
  14. private val cookieJar: CookieJar = builder.cookieJar
  15. private val cache: Cache? = builder.cache
  16. private val socketFactory: SocketFactory = builder.socketFactory
  17. private val sslSocketFactory: SSLSocketFactory?
  18. private val hostnameVerifier: HostnameVerifier = builder.hostnameVerifier
  19. private val certificatePinner: CertificatePinner
  20. private val proxyAuthenticator: Authenticator = builder.proxyAuthenticator
  21. private val authenticator: Authenticator = builder.authenticator
  22. private val connectionPool: ConnectionPool = builder.connectionPool
  23. private val dns: Dns = builder.dns
  24. private val followSslRedirects: Boolean = builder.followSslRedirects
  25. private val followRedirects: Boolean = builder.followRedirects
  26. private val retryOnConnectionFailure: Boolean = builder.retryOnConnectionFailure
  27. private val callTimeout: Int = builder.callTimeout
  28. private val connectTimeout: Int = builder.connectTimeout
  29. private val readTimeout: Int = builder.readTimeout
  30. private val writeTimeout: Int = builder.writeTimeout
  31. private val pingInterval: Int = builder.pingInterval
  32. private val internalCache: InternalCache? = builder.internalCache
  33. private val certificateChainCleaner: CertificateChainCleaner?
  34. ......
  35. /** Prepares the [request] to be executed at some point in the future. */
  36. override fun newCall(request: Request): Call {
  37. return RealCall.newRealCall(this, request, false /* for web socket */)
  38. }
  39. }

RealCall

RealCall是okhttp中任务的封装类

  1. companion object {
  2. fun newRealCall(
  3. client: OkHttpClient,
  4. originalRequest: Request,
  5. forWebSocket: Boolean
  6. ): RealCall {
  7. // Safely publish the Call instance to the EventListener.
  8. return RealCall(client, originalRequest, forWebSocket).apply {
  9. transmitter = Transmitter(client, this)
  10. }
  11. }
  12. }
  13. internal class RealCall private constructor(
  14. val client: OkHttpClient,
  15. /** The application's original request unadulterated by redirects or auth headers. */
  16. val originalRequest: Request,
  17. val forWebSocket: Boolean
  18. ) : Call {
  19. /**
  20. * There is a cycle between the [Call] and [Transmitter] that makes this awkward.
  21. * This is set after immediately after creating the call instance.
  22. */
  23. private lateinit var transmitter: Transmitter
  24. // Guarded by this.
  25. var executed: Boolean = false
  26. @Synchronized override fun isExecuted(): Boolean = executed
  27. override fun isCanceled(): Boolean = transmitter.isCanceled
  28. override fun request(): Request = originalRequest
  29. override fun execute(): Response {
  30. synchronized(this) {
  31. check(!executed) { "Already Executed" }
  32. executed = true
  33. }
  34. transmitter.timeoutEnter()
  35. transmitter.callStart()
  36. try {
  37. client.dispatcher().executed(this)
  38. return getResponseWithInterceptorChain()
  39. } finally {
  40. client.dispatcher().finished(this)
  41. }
  42. }
  43. override fun enqueue(responseCallback: Callback) {
  44. synchronized(this) {
  45. check(!executed) { "Already Executed" }
  46. executed = true
  47. }
  48. transmitter.callStart()
  49. client.dispatcher().enqueue(AsyncCall(responseCallback))
  50. }
  51. override fun cancel() {
  52. transmitter.cancel()
  53. }
  54. ...
  55. }

在异步任务的例子中,我们通常使用enqueue将我们的请求加入请求队列。
client.dispatcher().enqueue(AsyncCall(responseCallback))
这句话中,我们可以看到,我们新建了AsyncCall加入到OKHttpClient的dispatcher的队列中。

我们先看AsyncCall封装了什么

  1. internal inner class AsyncCall(
  2. private val responseCallback: Callback
  3. ) : NamedRunnable("OkHttp %s", redactedUrl()) {
  4. @Volatile private var callsPerHost = AtomicInteger(0)
  5. fun callsPerHost(): AtomicInteger = callsPerHost
  6. fun reuseCallsPerHostFrom(other: AsyncCall) {
  7. this.callsPerHost = other.callsPerHost
  8. }
  9. fun host(): String = originalRequest.url().host()
  10. fun request(): Request = originalRequest
  11. fun get(): RealCall = this@RealCall
  12. /**
  13. * Attempt to enqueue this async call on `executorService`. This will attempt to clean up
  14. * if the executor has been shut down by reporting the call as failed.
  15. */
  16. fun executeOn(executorService: ExecutorService) {
  17. assert(!Thread.holdsLock(client.dispatcher()))
  18. var success = false
  19. try {
  20. executorService.execute(this)
  21. success = true
  22. } catch (e: RejectedExecutionException) {
  23. val ioException = InterruptedIOException("executor rejected")
  24. ioException.initCause(e)
  25. transmitter.noMoreExchanges(ioException)
  26. responseCallback.onFailure(this@RealCall, ioException)
  27. } finally {
  28. if (!success) {
  29. client.dispatcher().finished(this) // This call is no longer running!
  30. }
  31. }
  32. }
  33. override fun execute() {
  34. var signalledCallback = false
  35. transmitter.timeoutEnter()
  36. try {
  37. val response = getResponseWithInterceptorChain()
  38. signalledCallback = true
  39. responseCallback.onResponse(this@RealCall, response)
  40. } catch (e: IOException) {
  41. if (signalledCallback) {
  42. // Do not signal the callback twice!
  43. Platform.get().log(INFO, "Callback failure for ${toLoggableString()}", e)
  44. } else {
  45. responseCallback.onFailure(this@RealCall, e)
  46. }
  47. } finally {
  48. client.dispatcher().finished(this)
  49. }
  50. }
  51. }

我们可以看到,AsyncCall主要提供了executeOn和execute两个方法。

executeOn

executeOn是AsyncCall自身的方法。它的主要内容是对异常的处理。如果一切正常,就用传入的ExecutorService执行当前AsyncCall。

execute

而execute是实现的Runnable的run方法。

  1. public abstract class NamedRunnable implements Runnable {
  2. protected final String name;
  3. public NamedRunnable(String format, Object... args) {
  4. this.name = Util.format(format, args);
  5. }
  6. @Override public final void run() {
  7. String oldName = Thread.currentThread().getName();
  8. Thread.currentThread().setName(name);
  9. try {
  10. execute();
  11. } finally {
  12. Thread.currentThread().setName(oldName);
  13. }
  14. }
  15. protected abstract void execute();
  16. }

我们可以看到,这个方法,只是为了给线程起名。
当AsyncCall在线程池中执行时,execute方法就会被调用。execute方法的主要逻辑是:
getResponseWithInterceptorChain,它的实现,我们再不展开,属于okhttp网络能力了。

铺垫了上面这么多,我们终于可以看看okhttp的任务队列如何设计的了。

Dispatcher

  1. private var idleCallback: Runnable? = null
  2. /** Executes calls. Created lazily. */
  3. private var executorService: ExecutorService? = null
  4. /** Ready async calls in the order they'll be run. */
  5. private val readyAsyncCalls = ArrayDeque<AsyncCall>()
  6. /** Running asynchronous calls. Includes canceled calls that haven't finished yet. */
  7. private val runningAsyncCalls = ArrayDeque<AsyncCall>()
  8. /** Running synchronous calls. Includes canceled calls that haven't finished yet. */
  9. private val runningSyncCalls = ArrayDeque<RealCall>()
  10. internal fun enqueue(call: AsyncCall) {
  11. synchronized(this) {
  12. readyAsyncCalls.add(call)
  13. // Mutate the AsyncCall so that it shares the AtomicInteger of an existing running call to
  14. // the same host.
  15. if (!call.get().forWebSocket) {
  16. val existingCall = findExistingCallWithHost(call.host())
  17. if (existingCall != null) call.reuseCallsPerHostFrom(existingCall)
  18. }
  19. }
  20. promoteAndExecute()
  21. }

这一段主要是AsyncCall的callsPerHost复用逻辑,注释说明比较清晰。如果有相同的AsyncCall存在于runningAsyncCalls中,则会增加callsPerHost。接下来,看一下promoteAndExecute的实现:

  1. private fun promoteAndExecute(): Boolean {
  2. assert(!Thread.holdsLock(this))
  3. val executableCalls = ArrayList<AsyncCall>()
  4. val isRunning: Boolean
  5. synchronized(this) {
  6. val i = readyAsyncCalls.iterator()
  7. while (i.hasNext()) {
  8. val asyncCall = i.next()
  9. if (runningAsyncCalls.size >= this.maxRequests) break // Max capacity.
  10. if (asyncCall.callsPerHost().get() >= this.maxRequestsPerHost) continue // Host max capacity.
  11. i.remove()
  12. asyncCall.callsPerHost().incrementAndGet()
  13. executableCalls.add(asyncCall)
  14. runningAsyncCalls.add(asyncCall)
  15. }
  16. isRunning = runningCallsCount() > 0
  17. }
  18. for (i in 0 until executableCalls.size) {
  19. val asyncCall = executableCalls[i]
  20. asyncCall.executeOn(executorService())
  21. }
  22. return isRunning
  23. }

promoteAndExecute方法,是将readyAsyncCalls队列中的任务,在最大任务数没有超标的情况下,移入runningAsyncCalls队列中。并对涉及转移的方法,调用executeOn方法。executeOn被调用后,就会执行到,RealCall中AsyncCall中的execute方法了。

小结

以上就是okhttp在请求和任务上的基本结构,还没有涉及到具体的网络请求。核心类是RealCall和Dispatcher,通过ArrayDeque和AsyncCall完成任务的调度。

如有问题,欢迎指正。