Android应用开发:网络工具——Volley(二)

引言

Android应用开发:网络工具——Volley(一)中结合Cloudant服务介绍了Volley的一般用法,其中包含了两种请求类型StringRequest和JsonObjectRequest。一般的请求任务相信都可以通过他们完成了,不过在千变万化的网络编程中,我们还是希望能够对请求类型、过程等步骤进行完全的把控,本文就从Volley源码角度来分析一下,一个网络请求在Volley中是如何运作的,也可以看作网络请求在Volley中的生命周期。


源头RequestQueue


在使用Volley前,必须有一个网络请求队列来承载请求,所以先分析一下这个请求队列是如何申请,如果运作的。在Volley.java中:

  1. /** 
  2.   * Creates a default instance of the worker pool and calls {@link RequestQueue#start()} on it. 
  3.   * 
  4.   * @param context A {@link Context} to use for creating the cache dir. 
  5.   * @param stack An {@link HttpStack} to use for the network, or null for default. 
  6.   * @return A started {@link RequestQueue} instance. 
  7.   */  
  8.  public static RequestQueue newRequestQueue(Context context, HttpStack stack) {  
  9.      File cacheDir = new File(context.getCacheDir(), DEFAULT_CACHE_DIR);  
  10.   
  11.      String userAgent = "volley/0";  
  12.      try {  
  13.          String packageName = context.getPackageName();  
  14.          PackageInfo info = context.getPackageManager().getPackageInfo(packageName, 0);  
  15.          userAgent = packageName + "/" + info.versionCode;  
  16.      } catch (NameNotFoundException e) {  
  17.      }  
  18.   
  19.      if (stack == null) {  
  20.          if (Build.VERSION.SDK_INT >= 9) {  
  21.              stack = new HurlStack();  
  22.          } else {  
  23.              // Prior to Gingerbread, HttpUrlConnection was unreliable.  
  24.              // See: http://android-developers.blogspot.com/2011/09/androids-http-clients.html  
  25.              stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent));  
  26.          }  
  27.      }  
  28.   
  29.      Network network = new BasicNetwork(stack);  
  30.   
  31.      RequestQueue queue = new RequestQueue(new DiskBasedCache(cacheDir), network);  
  32.      queue.start();  
  33.   
  34.      return queue;  
  35.  }  
  36.   
  37.  /** 
  38.   * Creates a default instance of the worker pool and calls {@link RequestQueue#start()} on it. 
  39.   * 
  40.   * @param context A {@link Context} to use for creating the cache dir. 
  41.   * @return A started {@link RequestQueue} instance. 
  42.   */  
  43.  public static RequestQueue newRequestQueue(Context context) {  
  44.      return newRequestQueue(context, null);  
  45.  }  

通常使用的是第二个接口,也就是只有一个参数的newRequestQueue(Context context),使stack默认为null。可以看到我们得到的RequestQueue是通过RequestQueue申请,然后又调用了其start方法,最后返回给我们的。接下来看一下RequestQueue的构造方法:

  1. /** 
  2.  * Creates the worker pool. Processing will not begin until {@link #start()} is called. 
  3.  * 
  4.  * @param cache A Cache to use for persisting responses to disk 
  5.  * @param network A Network interface for performing HTTP requests 
  6.  * @param threadPoolSize Number of network dispatcher threads to create 
  7.  * @param delivery A ResponseDelivery interface for posting responses and errors 
  8.  */  
  9. public RequestQueue(Cache cache, Network network, int threadPoolSize,  
  10.         ResponseDelivery delivery) {  
  11.     mCache = cache;  
  12.     mNetwork = network;  
  13.     mDispatchers = new NetworkDispatcher[threadPoolSize];  
  14.     mDelivery = delivery;  
  15. }  
  16.   
  17. /** 
  18.  * Creates the worker pool. Processing will not begin until {@link #start()} is called. 
  19.  * 
  20.  * @param cache A Cache to use for persisting responses to disk 
  21.  * @param network A Network interface for performing HTTP requests 
  22.  * @param threadPoolSize Number of network dispatcher threads to create 
  23.  */  
  24. public RequestQueue(Cache cache, Network network, int threadPoolSize) {  
  25.     this(cache, network, threadPoolSize,  
  26.             new ExecutorDelivery(new Handler(Looper.getMainLooper())));  
  27. }  
  28.   
  29. /** 
  30.  * Creates the worker pool. Processing will not begin until {@link #start()} is called. 
  31.  * 
  32.  * @param cache A Cache to use for persisting responses to disk 
  33.  * @param network A Network interface for performing HTTP requests 
  34.  */  
  35. public RequestQueue(Cache cache, Network network) {  
  36.     this(cache, network, DEFAULT_NETWORK_THREAD_POOL_SIZE);  
  37. }  
RequestQueue有三种构造方法,通过newRequestQueue(Context context)调用的是最后一种。创建了一个工作池,默认承载网络线程数量为4个。而后两种构造方法都会调用到第一个,进行了一些局部变量的赋值,并没有什么需要多说的,接下来看start()方法:

  1. public void start() {  
  2.     stop();  // Make sure any currently running dispatchers are stopped.  
  3.     // Create the cache dispatcher and start it.  
  4.     mCacheDispatcher = new CacheDispatcher(mCacheQueue, mNetworkQueue, mCache, mDelivery);  
  5.     mCacheDispatcher.start();  
  6.   
  7.     // Create network dispatchers (and corresponding threads) up to the pool size.  
  8.     for (int i = 0; i < mDispatchers.length; i++) {  
  9.         NetworkDispatcher networkDispatcher = new NetworkDispatcher(mNetworkQueue, mNetwork,  
  10.                 mCache, mDelivery);  
  11.         mDispatchers[i] = networkDispatcher;  
  12.         networkDispatcher.start();  
  13.     }  
  14. }  

首先进行了stop操作,将所有的执行者全部退出,从而确保当前没有任何正在工作的执行者。然后主要的工作就是开启一个CacheDispatcher和符合线程池数量的NetworkDispatcher。首先分析CacheDispatcher。


CacheDispatcher缓存操作


CacheDispatcher为缓存队列处理器,创建伊始就被责令开始工作start(),因为CacheDispatcher继承于Thread类,所以需要看一下它所复写的run方法:

  1. @Override  
  2. public void run() {  
  3.     if (DEBUG) VolleyLog.v("start new dispatcher");  
  4.     Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);  
  5.   
  6.     // Make a blocking call to initialize the cache.  
  7.     mCache.initialize(); //初始化一个缓存  
  8.   
  9.     while (true) {  
  10.         try {  
  11.             // Get a request from the cache triage queue, blocking until  
  12.             // at least one is available.  
  13.             final Request<?> request = mCacheQueue.take(); //在缓存序列中获取请求,阻塞操作  
  14.             request.addMarker("cache-queue-take");  
  15.   
  16.             // If the request has been canceled, don't bother dispatching it.  
  17.             if (request.isCanceled()) { //若该请求已经被取消了,则直接跳过  
  18.                 request.finish("cache-discard-canceled");  
  19.                 continue;  
  20.             }  
  21.   
  22.             // Attempt to retrieve this item from cache.  
  23.             Cache.Entry entry = mCache.get(request.getCacheKey()); //尝试在缓存中查找是否有缓存数据  
  24.             if (entry == null) {  
  25.                 request.addMarker("cache-miss"); //若没有则缓存丢失,证明这个请求并没有获得实施过,扔进网络请求队列中  
  26.                 // Cache miss; send off to the network dispatcher.  
  27.                 mNetworkQueue.put(request);  
  28.                 continue;  
  29.             }  
  30.   
  31.             // If it is completely expired, just send it to the network.  
  32.             if (entry.isExpired()) { //若请求已经过期,那么就要去获取最新的消息,所以依然丢进网络请求队列中  
  33.                 request.addMarker("cache-hit-expired");  
  34.                 request.setCacheEntry(entry);  
  35.                 mNetworkQueue.put(request);  
  36.                 continue;  
  37.             }  
  38.   
  39.             // We have a cache hit; parse its data for delivery back to the request.  
  40.             request.addMarker("cache-hit");  
  41.             Response<?> response = request.parseNetworkResponse(  
  42.                     new NetworkResponse(entry.data, entry.responseHeaders)); //请求有缓存数据且没有过期,那么可以进行解析,交给请求的parseNetworkReponse方法进行解析,这个方法我们可以在自定义个Request中进行复写自定义  
  43.             request.addMarker("cache-hit-parsed");  
  44.   
  45.             if (!entry.refreshNeeded()) { //如果请求有效且并不需要刷新,则丢进Delivery中处理,最终会触发如StringRequest这样的请求子类的onResponse或onErrorResponse  
  46.                 // Completely unexpired cache hit. Just deliver the response.  
  47.                 mDelivery.postResponse(request, response);  
  48.             } else { //请求有效,但是需要进行刷新,那么需要丢进网络请求队列中  
  49.                 // Soft-expired cache hit. We can deliver the cached response,  
  50.                 // but we need to also send the request to the network for  
  51.                 // refreshing.  
  52.                 request.addMarker("cache-hit-refresh-needed");  
  53.                 request.setCacheEntry(entry);  
  54.   
  55.                 // Mark the response as intermediate.  
  56.                 response.intermediate = true;  
  57.   
  58.                 // Post the intermediate response back to the user and have  
  59.                 // the delivery then forward the request along to the network.  
  60.                 mDelivery.postResponse(request, response, new Runnable() {  
  61.                     @Override  
  62.                     public void run() {  
  63.                         try {  
  64.                             mNetworkQueue.put(request);  
  65.                         } catch (InterruptedException e) {  
  66.                             // Not much we can do about this.  
  67.                         }  
  68.                     }  
  69.                 });  
  70.             }  
  71.   
  72.         } catch (InterruptedException e) {  
  73.             // We may have been interrupted because it was time to quit.  
  74.             if (mQuit) {  
  75.                 return;  
  76.             }  
  77.             continue;  
  78.         }  
  79.     }  
  80. }  

CacheDispatcher做了很多事情,之后再来慢慢的消化他们。现在先看一下我们的请求通过add之后到了哪里去。查看RequestQueue.java的add方法:

  1. /** 
  2.  * Adds a Request to the dispatch queue. 
  3.  * @param request The request to service 
  4.  * @return The passed-in request 
  5.  */  
  6. public <T> Request<T> add(Request<T> request) {  
  7.     // Tag the request as belonging to this queue and add it to the set of current requests.  
  8.     request.setRequestQueue(this);  
  9.     synchronized (mCurrentRequests) {  
  10.         mCurrentRequests.add(request); //加入到当前的队列中,是一个HashSet  
  11.     }  
  12.   
  13.     // Process requests in the order they are added.  
  14.     request.setSequence(getSequenceNumber());  
  15.     request.addMarker("add-to-queue");  
  16.   
  17.     // If the request is uncacheable, skip the cache queue and go straight to the network.若这个请求不需要被缓存,需要直接做网络请求,那么就直接加到网络请求队列中  
  18.     if (!request.shouldCache()) {  
  19.         mNetworkQueue.add(request);  
  20.         return request;  
  21.     }  
  22.   
  23.     // Insert request into stage if there's already a request with the same cache key in flight.  
  24.     synchronized (mWaitingRequests) {  
  25.         String cacheKey = request.getCacheKey(); // Volley中使用请求的URL作为存储的key  
  26.         if (mWaitingRequests.containsKey(cacheKey)) { //若等待的请求中有与所请求的URL相同的请求,则需要做层级处理  
  27.             // There is already a request in flight. Queue up.  
  28.             Queue<Request<?>> stagedRequests = mWaitingRequests.get(cacheKey);  
  29.             if (stagedRequests == null) {  
  30.                 stagedRequests = new LinkedList<Request<?>>();  
  31.             }  
  32.             stagedRequests.add(request);  
  33.             mWaitingRequests.put(cacheKey, stagedRequests); //若与已有的请求URL相同,则创建一个层级列表保存他们,然后再放入等待请求列表中  
  34.             if (VolleyLog.DEBUG) {  
  35.                 VolleyLog.v("Request for cacheKey=%s is in flight, putting on hold.", cacheKey);  
  36.             }  
  37.         } else {  
  38.             // Insert 'null' queue for this cacheKey, indicating there is now a request in  
  39.             // flight.  
  40.             mWaitingRequests.put(cacheKey, null); //若是一个全新的请求,则直接放入等待队列中,注意数据为null,只有多个url产生层级关系了才有数据  
  41.             mCacheQueue.add(request); //放入缓存队列中,缓存队列会对请求做处理  
  42.         }  
  43.         return request;  
  44.     }  
  45. }  

这里的mCacheQueue就是放入CacheDispatcher的那个阻塞队列,所以在add中添加到mCacheQueue后,因为CacheDispatcher已经运行起来了,所以CacheDispatcher会对刚刚加入的网络请求做处理。分析到这里,可以进行一下阶段性的梳理:

1. 我们的请求在加入到RequestQueue后,首先会加入到其实体类的mCurrentRequests列表中做本地管理

2. 如果之前已经存在了和本次请求相同URL的请求,那么会将层级关系保存在mWaitingRequests中,若没有则层级关系为null,同样也会保存在mWaitingRequests中

3. 对于没有层级关系(新的URL)的网络请求会直接放入mCacheQueue中让CacheDispatcher对其进行处理

分析到这里发现对于同一个URL的请求处理比较特殊,当第一次做某个网络请求A时候,A会直接放入缓存队列中由CacheDispatcher进行处理。下一次进行同一个URL的请求B时,若此时A还存在于mWaitingRequests队列中则B的请求被雪藏,不放入mCacheQueue缓存队列进行处理,只是等待。那么等待到什么时候呢?不难猜想到是需要等待A的请求完毕后才可以进行B的请求。归结到底就是需要知道mWaitingRequest是如何运作的?什么时候存储在其中的层级结构才会被拿出来进行请求。暂时记下这个问题,现在回头再去继续分析CacheDispatcher。CacheDispatcher对请求的处理可以归结为以下几种情况:


1. 对于取消的请求,直接表示为完成并跳过;

2. 对于尚未有应答数据的、数据过期、有明显标示需要刷新的请求直接丢入mNetworkQueue,mNetworkQueue同mCacheQueue一样,是一个阻塞队列;

3. 对于有应答数据且数据尚未过期的请求会出发Request的parseNetworkResponse方法进行数据解析,这个方法可以通过继承Request类进行复写(定制);

4. 对于有效应答(无论是否需要更新)都会用mDelivery进行应答,需要刷新的请求则会再次放入到mNetworkQueue中去。

对于(1)暂不做分析,后边会遇到。下边分析一下mNetworkQueue的运作原理,mNetworkQueue是在CacheDispatcher构造时传入的参数,通过RequestQueue的start()方法不难分析出相对应的处理器为NetworkDispatcher。


NetworkDispatcher网络处理

在RequestQueue的start()方法中,NetworkDispatcher存在多个,其数量等于RequestQueue构造时候传入的网络处理线程数量相等,默认为4个。

  1. public void start() {  
  2.     stop();  // Make sure any currently running dispatchers are stopped.  
  3.     // Create the cache dispatcher and start it.  
  4.     mCacheDispatcher = new CacheDispatcher(mCacheQueue, mNetworkQueue, mCache, mDelivery);  
  5.     mCacheDispatcher.start();  
  6.   
  7.     // Create network dispatchers (and corresponding threads) up to the pool size.  
  8.     for (int i = 0; i < mDispatchers.length; i++) {  
  9.         NetworkDispatcher networkDispatcher = new NetworkDispatcher(mNetworkQueue, mNetwork,  
  10.                 mCache, mDelivery);  
  11.         mDispatchers[i] = networkDispatcher;  
  12.         networkDispatcher.start();  
  13.     }  
  14. }  

每一个dispatcher被创造后都及时进行了start()操作,而NetworkDispatcher也是继承于Thread的类,那么之后需要分析其复写的run方法,在这之前先看一下它的构造方法:

  1. public NetworkDispatcher(BlockingQueue<Request<?>> queue,  
  2.         Network network, Cache cache,  
  3.         ResponseDelivery delivery) {  
  4.     mQueue = queue;  
  5.     mNetwork = network;  
  6.     mCache = cache;  
  7.     mDelivery = delivery;  
  8. }  
mQueue即为mNetworkQueue,这与CacheDispatcher中使用到的是同一个。而mNetwork默认是BasicNetwork,mCache为缓存,mDelivery为最终的消息配发者,之后会分析到。接下来看其复写的run()方法:

  1. @Override  
  2. public void run() {  
  3.     Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); //设置线程可后台运行,不会因为系统休眠而挂起  
  4.     Request<?> request;  
  5.     while (true) {  
  6.         try {  
  7.             // Take a request from the queue.  
  8.             request = mQueue.take(); //mQueue即为mNetworkQueue,从mNetworkQueue中获取请求,也就是说CacheDispatcher丢过来的请求是从这里被NetworkDispatcher获取到的。注意这里获取请求是阻塞的。  
  9.         } catch (InterruptedException e) { //退出操作,NetworkDispatcher被设置成退出时候发出中断请求  
  10.             // We may have been interrupted because it was time to quit.  
  11.             if (mQuit) {  
  12.                 return;  
  13.             }  
  14.             continue;  
  15.         }  
  16.   
  17.         try {  
  18.             request.addMarker("network-queue-take");  
  19.   
  20.             // If the request was cancelled already, do not perform the  
  21.             // network request.  
  22.             if (request.isCanceled()) { //若请求已经被取消,则标记为完成(被取消),然后继续下一个请求  
  23.                 request.finish("network-discard-cancelled");  
  24.                 continue;  
  25.             }  
  26.   
  27.             addTrafficStatsTag(request);  
  28.   
  29.             // Perform the network request.  
  30.             NetworkResponse networkResponse = mNetwork.performRequest(request); //使用BasicNetwork处理请求  
  31.             request.addMarker("network-http-complete");  
  32.   
  33.             // If the server returned 304 AND we delivered a response already,  
  34.             // we're done -- don't deliver a second identical response.  
  35.             if (networkResponse.notModified && request.hasHadResponseDelivered()) {  
  36.                 request.finish("not-modified");  
  37.                 continue;  
  38.             }  
  39.   
  40.             // Parse the response here on the worker thread.  
  41.             Response<?> response = request.parseNetworkResponse(networkResponse); //处理网络请求应答数据  
  42.             request.addMarker("network-parse-complete");  
  43.   
  44.             // Write to cache if applicable.  
  45.             // TODO: Only update cache metadata instead of entire record for 304s.  
  46.             if (request.shouldCache() && response.cacheEntry != null) {  
  47.                 mCache.put(request.getCacheKey(), response.cacheEntry);  
  48.                 request.addMarker("network-cache-written");  
  49.             }  
  50.   
  51.             // Post the response back.  
  52.             request.markDelivered(); //标记请求为已应答并做消息分发处理  
  53.             mDelivery.postResponse(request, response);  
  54.         } catch (VolleyError volleyError) {  
  55.             parseAndDeliverNetworkError(request, volleyError); //若产生Volley错误则会触发Request的parseNetworkError方法以及mDelivery的postError方法  
  56.         } catch (Exception e) {  
  57.             VolleyLog.e(e, "Unhandled exception %s", e.toString());  
  58.             mDelivery.postError(request, new VolleyError(e)); //对于未知错误,只会触发mDelivery的postError方法。  
  59.         }  
  60.     }  
  61. }  

mNetwork.performRequest是真正的网络请求实施的地方,这里对BasicNetwork不做分析。网络请求的回应是NetworkResponse类型,看一下这个类型是怎么样的:

  1. /** 
  2.   * Data and headers returned from {@link Network#performRequest(Request)}. 
  3.   */  
  4.  public class NetworkResponse {  
  5.      /** 
  6.       * Creates a new network response. 
  7.       * @param statusCode the HTTP status code 
  8.       * @param data Response body 
  9.       * @param headers Headers returned with this response, or null for none 
  10.       * @param notModified True if the server returned a 304 and the data was already in cache 
  11.       */  
  12.      public NetworkResponse(int statusCode, byte[] data, Map<String, String> headers,  
  13.              boolean notModified) {  
  14.          this.statusCode = statusCode;  
  15.          this.data = data;  
  16.          this.headers = headers;  
  17.          this.notModified = notModified;  
  18.      }  
  19.   
  20.      public NetworkResponse(byte[] data) {  
  21.          this(HttpStatus.SC_OK, data, Collections.<String, String>emptyMap(), false);  
  22.      }  
  23.   
  24.      public NetworkResponse(byte[] data, Map<String, String> headers) {  
  25.          this(HttpStatus.SC_OK, data, headers, false);  
  26.      }  
  27.   
  28.      /** The HTTP status code. */  
  29.      public final int statusCode;  
  30.   
  31.      /** Raw data from this response. */  
  32.      public final byte[] data;  
  33.   
  34.      /** Response headers. */  
  35.      public final Map<String, String> headers;  
  36.   
  37.      /** True if the server returned a 304 (Not Modified). */  
  38.      public final boolean notModified;  
  39.  }  
NetworkResponse保存了请求的回应数据,包括数据本身和头,还有状态码以及其他相关信息。根据请求类型的不同,对回应数据的处理方式也各有不同,例如回应是String和Json的区别。所以自然而然的网络请求类型需要对它获得的回应数据自行处理,也就触发了Request子类的parseNetworkResponse方法,下边以StringRequest为例进行分析:

  1. @Override  
  2. protected Response<String> parseNetworkResponse(NetworkResponse response) {  
  3.     String parsed;  
  4.     try {  
  5.         parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));  
  6.     } catch (UnsupportedEncodingException e) {  
  7.         parsed = new String(response.data);  
  8.     }  
  9.     return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));  
  10. }  
StringRequest中对于回应首先尝试解析数据和辨别头数据编码类型,若失败则只解析数据部分。最终都是触发Request的success方法,参数中还使用Volley自带的HttpHeaderParser对头信息进行了解析。需要看一下Response的success方法究竟做了什么,鉴于Response类总共没有多少代码,就全部拿出来做分析了:

  1. public class Response<T> {  
  2.   
  3.     /** 处理解析过的回应信息的回调接口 */  
  4.     public interface Listener<T> {  
  5.         /** 当接收到回应后 */  
  6.         public void onResponse(T response);  
  7.     }  
  8.   
  9.     /** 处理错误回应的回调接口 */  
  10.     public interface ErrorListener {  
  11.         /** 
  12.          * 错误发生时的回调接口 
  13.          */  
  14.         public void onErrorResponse(VolleyError error);  
  15.     }  
  16.   
  17.     /** 返回一个包含已解析结果的成功回应 */  
  18.     public static <T> Response<T> success(T result, Cache.Entry cacheEntry) {  
  19.         return new Response<T>(result, cacheEntry);  
  20.     }  
  21.   
  22.     /** 
  23.      * 返回错误回应,包含错误码以及可能的其他消息 
  24.      */  
  25.     public static <T> Response<T> error(VolleyError error) {  
  26.         return new Response<T>(error);  
  27.     }  
  28.   
  29.     /** 解析过的响应信息,错误时为null */  
  30.     public final T result;  
  31.   
  32.     /** 响应的缓存数据,错误时为null */  
  33.     public final Cache.Entry cacheEntry;  
  34.   
  35.     /** 详细的错误信息 */  
  36.     public final VolleyError error;  
  37.   
  38.     /** 此回应软件希望得到第二次回应则为true,即需要刷新 */  
  39.     public boolean intermediate = false;  
  40.   
  41.     /** 
  42.      * 返回true代表回应成功,没有错误。有错误则为false 
  43.      */  
  44.     public boolean isSuccess() {  
  45.         return error == null;  
  46.     }  
  47.   
  48.   
  49.     private Response(T result, Cache.Entry cacheEntry) {  
  50.         this.result = result;  
  51.         this.cacheEntry = cacheEntry;  
  52.         this.error = null;  
  53.     }  
  54.   
  55.     private Response(VolleyError error) {  
  56.         this.result = null;  
  57.         this.cacheEntry = null;  
  58.         this.error = error;  
  59.     }  
  60. }  
这就是网络响应的类,很简单,成功或错误都会直接进行标记,通过isSuccess接口提供外部查询。如果响应成功,则消息保存在result中,解析头信息得到的缓存数据保存在cacheEntry中。

Request作为基类,Volley自带的又代表性的其扩展类又StringRequest和JsonObjectRequest,如果开发者有比较大的自定义需求就需要继承Request复写内部一些重要的方法。同时mDelivery出场的机会这么多,为什么他总出现在处理请求的地方呢?下边就对它和Request一起进行分析,其中Request依然以StringRequest为例。

ExecutorDelivery消息分发者与Request请求

mDelivery类型为ResponseDelivery,实为接口类型:

  1. public interface ResponseDelivery {  
  2.     /** 
  3.      * Parses a response from the network or cache and delivers it. 
  4.      */  
  5.     public void postResponse(Request<?> request, Response<?> response);  
  6.   
  7.     /** 
  8.      * Parses a response from the network or cache and delivers it. The provided 
  9.      * Runnable will be executed after delivery. 
  10.      */  
  11.     public void postResponse(Request<?> request, Response<?> response, Runnable runnable);  
  12.   
  13.     /** 
  14.      * Posts an error for the given request. 
  15.      */  
  16.     public void postError(Request<?> request, VolleyError error);  
  17. }  

三个接口其中两个是回应网络应答的,最后一个回应网络错误。追溯RequestQueue构造的时候,默认的分发者为ExecutorDelivery:

  1. public RequestQueue(Cache cache, Network network, int threadPoolSize) {  
  2.     this(cache, network, threadPoolSize,  
  3.             new ExecutorDelivery(new Handler(Looper.getMainLooper())));  
  4. }  

可见,消息分发者工作在主线程上。常见的分发者所做的工作有:

  1. @Override  
  2. public void postResponse(Request<?> request, Response<?> response) { //发出响应  
  3.     postResponse(request, response, null);  
  4. }  
  5.   
  6. @Override  
  7. public void postResponse(Request<?> request, Response<?> response, Runnable runnable) { //发出响应  
  8.     request.markDelivered();  
  9.     request.addMarker("post-response");  
  10.     mResponsePoster.execute(new ResponseDeliveryRunnable(request, response, runnable));  
  11. }  
  12.   
  13. @Override  
  14. public void postError(Request<?> request, VolleyError error) { //发出错误响应  
  15.     request.addMarker("post-error");  
  16.     Response<?> response = Response.error(error);  
  17.     mResponsePoster.execute(new ResponseDeliveryRunnable(request, response, null));  
  18. }  
这里发现一个问题,其实在NetworkDispatcher中的request.markDelivered()是多余的,在postResponse中已经执行了。无论是正常的响应还是错误都会执行ResponseDeliveryRunnable:

  1. private class ResponseDeliveryRunnable implements Runnable {  
  2.          private final Request mRequest;  
  3.          private final Response mResponse;  
  4.          private final Runnable mRunnable;  
  5.   
  6.          public ResponseDeliveryRunnable(Request request, Response response, Runnable runnable) {  
  7.              mRequest = request;  
  8.              mResponse = response;  
  9.              mRunnable = runnable; //若指定了runnable,如上面分析的在网络请求有效但是需要更新的时候会指定一个runnable的  
  10.          }  
  11.   
  12.          @SuppressWarnings("unchecked")  
  13.          @Override  
  14.          public void run() {  
  15.              // If this request has canceled, finish it and don't deliver.  
  16.              if (mRequest.isCanceled()) { //若请求被取消,结束并做标记  
  17.                  mRequest.finish("canceled-at-delivery");  
  18.                  return;  
  19.              }  
  20.   
  21.              // Deliver a normal response or error, depending.  
  22.              if (mResponse.isSuccess()) { //若请求成功则处理回应  
  23.                  mRequest.deliverResponse(mResponse.result);  
  24.              } else {  //若不成功则处理错误  
  25.                  mRequest.deliverError(mResponse.error);  
  26.              }  
  27.   
  28.              // If this is an intermediate response, add a marker, otherwise we're done  
  29.              // and the request can be finished.  
  30.              if (mResponse.intermediate) {  
  31.                  mRequest.addMarker("intermediate-response");  
  32.              } else {  
  33.                  mRequest.finish("done");  
  34.              }  
  35.   
  36.              // If we have been provided a post-delivery runnable, run it.  
  37.              if (mRunnable != null) { //如果指定了额外的runnable这里还会对它进行执行  
  38.                  mRunnable.run();  
  39.              }  
  40.         }  
  41.      }  

Delivery作为网络回应的分发、处理者,对回应数据进行了最后一层的把关。而当Delivery查询回应是否成功时,因为Request已经对回应信息做过处理(检查其成功还是错误),所以可以查询到正确的状态。若查询到回应成功则会触发Request的deliverResponse方法(以StringRequest为例):

  1. @Override  
  2. protected void deliverResponse(String response) {  
  3.     mListener.onResponse(response);  
  4. }  
其实就是触发了用户自定义的网络响应监听器,mListener在StringRequest的构造中进行赋值:

  1. public StringRequest(int method, String url, Listener<String> listener,  
  2.         ErrorListener errorListener) {  
  3.     super(method, url, errorListener);  
  4.     mListener = listener;  
  5. }  
  6.   
  7. public StringRequest(String url, Listener<String> listener, ErrorListener errorListener) {  
  8.     this(Method.GET, url, listener, errorListener);  
  9. }  
当查询到网络回应数据不成功时候将触发Request的deliverError方法,这个方法StringRequest并没有复写,所以追溯到其父类Request中:

  1. public void deliverError(VolleyError error) {  
  2.     if (mErrorListener != null) {  
  3.         mErrorListener.onErrorResponse(error);  
  4.     }  
  5. }  
这里mErrorListener也是用户在使用Volley时候自定的错误监听器,在StringRequest中并没有处理,是通过super执行Request的构造方法进行赋值的:

  1. public Request(int method, String url, Response.ErrorListener listener) {  
  2.     mMethod = method;  
  3.     mUrl = url;  
  4.     mErrorListener = listener;  
  5.     setRetryPolicy(new DefaultRetryPolicy());  
  6.   
  7.     mDefaultTrafficStatsTag = findDefaultTrafficStatsTag(url);  
  8. }  
当这个请求已经完整的确定完成后,Delivery会通知Request进行结束操作——finish:

  1. void finish(final String tag) {  
  2.     if (mRequestQueue != null) { //若请求队列有效,则在请求队列中标记当前请求为结束  
  3.         mRequestQueue.finish(this);  
  4.     }  //之后都是日志相关,不做分析  
  5.     if (MarkerLog.ENABLED) {  
  6.         final long threadId = Thread.currentThread().getId();  
  7.         if (Looper.myLooper() != Looper.getMainLooper()) {  
  8.             // If we finish marking off of the main thread, we need to  
  9.             // actually do it on the main thread to ensure correct ordering.  
  10.             Handler mainThread = new Handler(Looper.getMainLooper());  
  11.             mainThread.post(new Runnable() {  
  12.                 @Override  
  13.                 public void run() {  
  14.                     mEventLog.add(tag, threadId);  
  15.                     mEventLog.finish(this.toString());  
  16.                 }  
  17.             });  
  18.             return;  
  19.         }  
  20.   
  21.         mEventLog.add(tag, threadId);  
  22.         mEventLog.finish(this.toString());  
  23.     } else {  
  24.         long requestTime = SystemClock.elapsedRealtime() - mRequestBirthTime;  
  25.         if (requestTime >= SLOW_REQUEST_THRESHOLD_MS) {  
  26.             VolleyLog.d("%d ms: %s", requestTime, this.toString());  
  27.         }  
  28.     }  
  29. }  

mRequestQueue为RequestQueue类型,在开篇中就分析了RequestQueue,相关的还有一个问题当时没有进行挖掘,即mWaitingQueue中保留的相同URL的多个请求层级何时才能够被触发,下边分析mRequestQueue的finish方法就能解开这个疑问了:

  1. void finish(Request<?> request) {  
  2.     // Remove from the set of requests currently being processed.  
  3.     synchronized (mCurrentRequests) {  
  4.         mCurrentRequests.remove(request); //当请求已完成,会从mCurrentRequests队列中被移除掉  
  5.     }  
  6.   
  7.     if (request.shouldCache()) { //默认是true的,除非你调用Request的setShouldCache方法主动设定  
  8.         synchronized (mWaitingRequests) {  
  9.             String cacheKey = request.getCacheKey(); //获取cacheKey,前边说过就是URL  
  10.             Queue<Request<?>> waitingRequests = mWaitingRequests.remove(cacheKey); //移除列表中的这个请求,同时取出其可能存在的层级关系  
  11.             if (waitingRequests != null) {  
  12.                 if (VolleyLog.DEBUG) {  
  13.                     VolleyLog.v("Releasing %d waiting requests for cacheKey=%s.",  
  14.                             waitingRequests.size(), cacheKey);  
  15.                 }  
  16.                 // Process all queued up requests. They won't be considered as in flight, but  
  17.                 // that's not a problem as the cache has been primed by 'request'.  
  18.                 mCacheQueue.addAll(waitingRequests); //若真的有层级关系,那么将其他的请求全部加入到mCacheQueue中交由CacheDispatcher处理  
  19.             }  
  20.         }  
  21.     }  
  22. }  
好了,最终待定的问题也解决了,这就是一个Request网络请求在Volley中的来龙去脉。


总结


1. 当一个RequestQueue被成功申请后会开启一个CacheDispatcher(缓存调度器)和4个(默认)NetworkDispatcher(网络请求调度器);

2. CacheDispatcher缓存调度器最为第一层缓冲,开始工作后阻塞的从缓存序列mCacheQueue中取得请求:

  a. 对于已经取消了的请求,直接标记为跳过并结束这个请求

  b. 全新或过期的请求,直接丢入mNetworkQueue中交由N个NetworkDispatcher进行处理

  c. 已获得缓存信息(网络应答)却没有过期的请求,交由Request的parseNetworkResponse进行解析,从而确定此应答是否成功。然后将请求和应答交由Delivery分发者进行处理,如果需要更新缓存那么该请求还会被放入mNetworkQueue中

3. 用户将请求Request add到RequestQueue之后:

  a. 对于不需要缓存的请求(需要额外设置,默认是需要缓存)直接丢入mNetworkQueue交由N个NetworkDispatcher处理;

  b. 对于需要缓存的,全新的请求加入到mCacheQueue中给CacheDispatcher处理

  c. 需要缓存,但是缓存列表中已经存在了相同URL的请求,放在mWaitingQueue中做暂时雪藏,待之前的请求完毕后,再重新添加到mCacheQueue中;

4. 网络请求调度器NetworkDispatcher作为网络请求真实发生的地方,对消息交给BasicNetwork进行处理,同样的,请求和结果都交由Delivery分发者进行处理;

5. Delivery分发者实际上已经是对网络请求处理的最后一层了,在Delivery对请求处理之前,Request已经对网络应答进行过解析,此时应答成功与否已经设定。而后Delivery根据请求所获得的应答情况做不同处理:

  a. 若应答成功,则触发deliverResponse方法,最终会触发开发者为Request设定的Listener

  b. 若应答失败,则触发deliverError方法,最终会触发开发者为Request设定的ErrorListener

处理完后,一个Request的生命周期就结束了,Delivery会调用Request的finish操作,将其从mRequestQueue中移除,与此同时,如果等待列表中存在相同URL的请求,则会将剩余的层级请求全部丢入mCacheQueue交由CacheDispatcher进行处理。


一个Request的生命周期:

1. 通过add加入mRequestQueue中,等待请求被执行;

2. 请求执行后,调用自身的parseNetworkResponse对网络应答进行处理,并判断这个应答是否成功;

3. 若成功,则最终会触发自身被开发者设定的Listener;若失败,最终会触发自身被开发者设定的ErrorListener。


至此Volley中网络请求的来龙去脉分析清楚了,如果我们因为一些原因需要继承Request来自定义自己的Request,最需要注意的就是parseNetworkResponse方法的复写,此方法对请求之后的命运有决定性的作用。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
编译原理是计算机专业的一门核心课程,旨在介绍编译程序构造的一般原理和基本方法。编译原理不仅是计算机科学理论的重要组成部分,也是实现高效、可靠的计算机程序设计的关键。本文将对编译原理的基本概念、发展历程、主要内容和实际应用进行详细介绍编译原理是计算机专业的一门核心课程,旨在介绍编译程序构造的一般原理和基本方法。编译原理不仅是计算机科学理论的重要组成部分,也是实现高效、可靠的计算机程序设计的关键。本文将对编译原理的基本概念、发展历程、主要内容和实际应用进行详细介绍编译原理是计算机专业的一门核心课程,旨在介绍编译程序构造的一般原理和基本方法。编译原理不仅是计算机科学理论的重要组成部分,也是实现高效、可靠的计算机程序设计的关键。本文将对编译原理的基本概念、发展历程、主要内容和实际应用进行详细介绍编译原理是计算机专业的一门核心课程,旨在介绍编译程序构造的一般原理和基本方法。编译原理不仅是计算机科学理论的重要组成部分,也是实现高效、可靠的计算机程序设计的关键。本文将对编译原理的基本概念、发展历程、主要内容和实际应用进行详细介绍编译原理是计算机专业的一门核心课程,旨在介绍编译程序构造的一般原理和基本

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值