Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Volley 源碼解析(一)——從初始化到請求分發

編輯:關於 Android 程式設計

緣起


在現在這家公司待了差不多一年,項目裡的網絡請求一直用的是 Volley。以前對它的認識基本來自各家博客:知道怎麼調、大概什麼原理。等到項目寫得差不多了,回頭一想,除了「會用」,剩下的細節幾乎都忘了。於是索性沉下來把源碼認真讀一遍。

先放一張整體流程圖,對著圖看代碼會輕ancing不少。

源碼解析


1. Volley 的初始化

 public static RequestQueue newRequestQueue(Context context, HttpStack stack) { File cacheDir = new File(context.getCacheDir(), "volley"); String userAgent = "volley/0"; try { String network = context.getPackageName(); PackageInfo queue = context.getPackageManager().getPackageInfo(network, 0); userAgent = network + "/" + queue.versionCode; } catch (NameNotFoundException var6) { ; } if(stack == null) { if(VERSION.SDK_INT >= 9) { stack = new HurlStack(); } else { stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent)); } } BasicNetwork network1 = new BasicNetwork((HttpStack)stack); RequestQueue queue1 = new RequestQueue(new DiskBasedCache(cacheDir), network1); queue1.start(); return queue1; }

這段做的事可以拆成三步。首先確定一個用於磁碟緩存的目錄,交給 DiskBasedCache 打理——它是 Cache 接口唯一的官方實現,內部細節這裡暫不糾結。接著根據系統版本挑選網絡層:3.0 及以上用 HttpUrlConnection(封裝為 HurlStack),更低版本則退回 HttpClient。最後把 HttpStack 包進 BasicNetwork,再與 Cache 一起組裝出 RequestQueue。這一步用的是典型的適配器模式,把不同版本的網絡 API 統一到同一個接口背後。

2. 構造請求隊列

  public RequestQueue(Cache cache, Network network, int threadPoolSize, ResponseDelivery delivery) { this.mSequenceGenerator = new AtomicInteger(); this.mWaitingRequests = new HashMap(); this.mCurrentRequests = new HashSet(); this.mCacheQueue = new PriorityBlockingQueue(); this.mNetworkQueue = new PriorityBlockingQueue(); this.mCache = cache; this.mNetwork = network; this.mDispatchers = new NetworkDispatcher[threadPoolSize]; this.mDelivery = delivery; } 

構造方法裡一口氣初始化了一大批成員,把它們逐一弄清楚,Volley 的骨架也就清楚大半了:

  • mSequenceGenerator:序列號生成器,等於給每個 Request 發一個身份標識。
  • mWaitingRequests:一個 Map,內部維護著若干等待隊列,體現的是 Volley 對重複請求的合併策略。
  • mCurrentRequests:記錄當前正在處理中的 Request 集合。
  • mCacheQueue:緩存隊列,Request 先進這裡;能命中就不必走網絡。
  • mNetworkQueue:網絡請求隊列,網絡分發者從這裡取任務。
  • mCache:傳入的 DiskBasedCache,即磁碟緩存。
  • mNetwork:傳入的 BasicNetwork,本質上就是對 Http 連接的一層封裝。
  • mDispatchers:網絡請求分發者數組,負責從網絡隊列取 Request 並執行。

還有個 mDelivery,也就是「傳達者」,負責在請求處理完畢後把結果送回 UI 線程。它是怎麼做到跨線程投遞的?答案很樸素——內部封裝了一個綁定主線程 Looper 的 Handler:

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

ExecutorDelivery 是 mDelivery 的默認實現:拿到主線程的 Looper 之後,把消息丟進 MessageQueue,由主線程的 Handler 取出並執行,UI 更新於是得以完成。

還有一個成員此處尚未初始化,留到下一步才創建,那就是 mCacheDispatcher——緩存分發者,專門從 mCacheQueue 中取 Request。

3. 啟動輪循

  public void start() { this.stop(); this.mCacheDispatcher = new CacheDispatcher(this.mCacheQueue, this.mNetworkQueue, this.mCache, this.mDelivery); this.mCacheDispatcher.start(); for(int i = 0; i < this.mDispatchers.length; ++i) { NetworkDispatcher networkDispatcher = new NetworkDispatcher(this.mNetworkQueue, this.mNetwork, this.mCache, this.mDelivery); this.mDispatchers[i] = networkDispatcher; networkDispatcher.start(); } }

代碼不長,但一此行就拉起了整套併發體系。緩存分發者與網絡分發者都繼承自 Thread,所以一次 start() 等於啟動了多條線程:緩存線程固定一條,網絡線程默認四條,合計五條。這也是 Volley 併發能力的來源。

4. 添加請求

 public Request add(Request request) { request.setRequestQueue(this); Set var2 = this.mCurrentRequests; synchronized(this.mCurrentRequests) { this.mCurrentRequests.add(request); } request.setSequence(this.getSequenceNumber()); request.addMarker("add-to-queue"); if(!request.shouldCache()) { this.mNetworkQueue.add(request); return request; } else { Map var7 = this.mWaitingRequests; synchronized(this.mWaitingRequests) { String cacheKey = request.getCacheKey(); if(this.mWaitingRequests.containsKey(cacheKey)) { Object stagedRequests = (Queue)this.mWaitingRequests.get(cacheKey); if(stagedRequests == null) { stagedRequests = new LinkedList(); } ((Queue)stagedRequests).add(request); this.mWaitingRequests.put(cacheKey, stagedRequests); if(VolleyLog.DEBUG) { VolleyLog.v("Request for cacheKey=%s is in flight, putting on hold.", new Object[]{cacheKey}); } } else { this.mWaitingRequests.put(cacheKey, (Object)null); this.mCacheQueue.add(request); } return request; } } }

直接看核心分支:如果開發者關閉了緩存,Request 被直接丟進網絡隊列,交給網絡分發者;若允許緩存,則先看 mWaitingRequests 裡有沒有相同的 cacheKey——沒有就投進緩存隊列並把該 key 佔位為 null,有則掛到這個 key 對應的等待隊列裡排隊。

初次讀到這段時我也犯糊塗,打斷點跟了一遍才想明白:第一次請求進來時 map 是空的,於是進入緩存隊列並佔位;第二次相同 cacheKey 的請求進來,發現 key 已存在,就被暫存進等待隊列。這樣做的目的是把同一資源的並發請求合併成一次真實網絡訪問,節省流量也避免重複加載。可能有人會擔心:如果一個請求結束很久後又來一個同 key 請求,會不會被永久攔住?不會——請求處理完成時,分發者會調用 Request 中的 finish(),把 mWaitingRequests 中對應的緩存清理掉:

  void finish(Request request) { Set var2 = this.mCurrentRequests; synchronized(this.mCurrentRequests) { this.mCurrentRequests.remove(request); } if(request.shouldCache()) { Map var7 = this.mWaitingRequests; synchronized(this.mWaitingRequests) { String cacheKey = request.getCacheKey(); Queue waitingRequests = (Queue)this.mWaitingRequests.remove(cacheKey); if(waitingRequests != null) { if(VolleyLog.DEBUG) { VolleyLog.v("Releasing %d waiting requests for cacheKey=%s.", new Object[]{Integer.valueOf(waitingRequests.size()), cacheKey}); } this.mCacheQueue.addAll(waitingRequests); } } } }

這樣一來邏輯就閉環了:每個 Request 都持有回填埋它的 RequestQueue 引用,處理完畢後調用 finish(),被暫存的等待請求會被重新放回緩存隊列,繼續各自的流程。

5. 緩存分發者

  public void run() { if (DEBUG) VolleyLog.v("start new dispatcher"); Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); // Make a blocking call to initialize the cache. mCache.initialize(); while (true) { try { // Get a request from the cache triage queue, blocking until // at least one is available. final Request request = mCacheQueue.take(); request.addMarker("cache-queue-take"); // If the request has been canceled, don't bother dispatching it. if (request.isCanceled()) { request.finish("cache-discard-canceled"); continue; } // Attempt to retrieve this item from cache. Cache.Entry entry = mCache.get(request.getCacheKey()); if (entry == null) { request.addMarker("cache-miss"); // Cache miss; send off to the network dispatcher. mNetworkQueue.put(request); continue; } // If it is completely expired, just send it to the network. if (entry.isExpired()) { request.addMarker("cache-hit-expired"); request.setCacheEntry(entry); mNetworkQueue.put(request); continue; } // We have a cache hit; parse its data for delivery back to the request. request.addMarker("cache-hit"); Response<?> response = request.parseNetworkResponse( new NetworkResponse(entry.data, entry.responseHeaders)); request.addMarker("cache-hit-parsed"); if (!entry.refreshNeeded()) { // Completely unexpired cache hit. Just deliver the response. mDelivery.postResponse(request, response); } else { // Soft-expired cache hit. We can deliver the cached response, // but we need to also send the request to the network for // refreshing. request.addMarker("cache-hit-refresh-needed"); request.setCacheEntry(entry); // Mark the response as intermediate. response.intermediate = true; // Post the intermediate response back to the user and have // the delivery then forward the request along to the network. mDelivery.postResponse(request, response, new Runnable() { @Override public void run() { try { mNetworkQueue.put(request); } catch (InterruptedException e) { // Not much we can do about this. } } }); } } catch (InterruptedException e) { // We may have been interrupted because it was time to quit. if (mQuit) { return; } continue; } } }

流程是這樣的:先做一次阻塞式的緩存初始化,然後進入死循環。每輪從緩存隊列取一個 Request,若已被取消就直接丟棄;否則查緩存——沒命中就轉投網絡隊列;命中但已完全過期,同樣轉投網絡;命中且有效,則解析出 Response 交給傳達者更新界面。

值得留意的是「軟過期」分支:當 refreshNeeded() 為真時,Volley 會先把舊數據當作中間結果回給 UI(響應更快),同時把請求轉發到網絡隊列去拉新數據,回來後再刷新一次。這是一種典型的「先舊後新」策略。

另外注意 mCacheQueue.take() 是阻塞操作,隊列為空時線程就停在這裡等待,並不會空轉消耗 CPU。下面的網絡分發者同理。

6. 網絡分發者

  @Override public void run() { Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); Request request; while (true) { try { // Take a request from the queue. request = mQueue.take(); } catch (InterruptedException e) { // We may have been interrupted because it was time to quit. if (mQuit) { return; } continue; } try { request.addMarker("network-queue-take"); // If the request was cancelled already, do not perform the // network request. if (request.isCanceled()) { request.finish("network-discard-cancelled"); continue; } // Tag the request (if API >= 14) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { TrafficStats.setThreadStatsTag(request.getTrafficStatsTag()); } // Perform the network request. NetworkResponse networkResponse = mNetwork.performRequest(request); request.addMarker("network-http-complete"); // If the server returned 304 AND we delivered a response already, // we're done -- don't deliver a second identical response. if (networkResponse.notModified && request.hasHadResponseDelivered()) { request.finish("not-modified"); continue; } // Parse the response here on the worker thread. Response<?> response = request.parseNetworkResponse(networkResponse); request.addMarker("network-parse-complete"); // Write to cache if applicable. if (request.shouldCache() && response.cacheEntry != null) { mCache.put(request.getCacheKey(), response.cacheEntry); request.addMarker("network-cache-written"); } // Post the response back. request.markDelivered(); mDelivery.postResponse(request, response); } catch (VolleyError volleyError) { parseAndDeliverNetworkError(request, volleyError); } catch (Exception e) { VolleyLog.e(e, "Unhandled exception %s", e.toString()); mDelivery.postError(request, new VolleyError(e)); } } } 

逐步拆解:從網絡隊列取出 Request,若已取消則直接 finish;隨後交給 BasicNetwork 執行真正的請求,拿回封裝了狀態碼、響應頭與響應體的 NetworkResponse。若返回 304 且此前已經投遞過結果,說明內容未變,直接結束;否則調用 parseNetworkResponse 解析數據,需要緩存時寫入磁碟,最後通過傳達者把結果送回 UI,並標記該請求已投遞。

解析環節以 StringRequest 為例:

  @Override protected Response<String> parseNetworkResponse(NetworkResponse response) { String parsed; try { parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers)); } catch (UnsupportedEncodingException e) { parsed = new String(response.data); } return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response)); }

緩存頭的解析則都在 HttpHeaderParser 中完成:

  public static Entry parseCacheHeaders(NetworkResponse response) { long now = System.currentTimeMillis(); Map headers = response.headers; long serverDate = 0L; long serverExpires = 0L; long softExpire = 0L; long maxAge = 0L; boolean hasCacheControl = false; String serverEtag = null; String headerValue = (String)headers.get("Date"); if(headerValue != null) { serverDate = parseDateAsEpoch(headerValue); } headerValue = (String)headers.get("Cache-Control"); if(headerValue != null) { hasCacheControl = true; String[] entry = headerValue.split(","); for(int i = 0; i < entry.length; ++i) { String token = entry[i].trim(); if(token.equals("no-cache") || token.equals("no-store")) { return null; } if(token.startsWith("max-age=")) { try { maxAge = Long.parseLong(token.substring(8)); } catch (Exception var19) { ; } } else if(token.equals("must-revalidate") || token.equals("proxy-revalidate")) { maxAge = 0L; } } } headerValue = (String)headers.get("Expires"); if(headerValue != null) { serverExpires = parseDateAsEpoch(headerValue); } serverEtag = (String)headers.get("ETag"); if(hasCacheControl) { softExpire = now + maxAge * 1000L; } else if(serverDate > 0L && serverExpires >= serverDate) { softExpire = now + (serverExpires - serverDate); } Entry var20 = new Entry(); var20.data = response.data; var20.etag = serverEtag; var20.softTtl = softExpire; var20.ttl = var20.softTtl; var20.serverDate = serverDate; var20.responseHeaders = headers; return var20; }

這裡解析的都是 HTTP 協議層面的緩存控制字段:Cache-Control(需要服務端配合才會下發,其中的 no-cache、no-store 直接導致不緩存)、Expires 以及 ETag。需要明確的是,這些屬於 HTTP 應用層的緩存語義,與 Volley 自身的隊列機制是兩件事,只是 Volley 順手把它們落成了自己的 Cache.Entry。

總結


把流程圖和代碼對起來看,整條鏈路就很清晰了:網絡請求進來後被封裝成 Request,先在緩存隊列中找;命中且未過期就直接通過 Handler 更新 UI;否則轉入網絡隊列,由四條網絡線程取出、執行、解析,寫入磁碟緩存,最後同樣交給傳達者回主線程刷新界面。

最大的體會是:別人寫的解析文章看得再明白,那也是別人的東西,放一段時間照樣忘乾淨;只有親手把源碼跟一遍、打斷點走一遍,知識才真正長在自己身上。若還能照著思路自己實現一個mini版,理解會更深一層。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved