編輯:關於 Android 程式設計
Cache 是 Volley 最核心的組成部分之一,Volley 在這上面花了不少心思。本文順著 Volley 的源碼脈絡,帶你看清楚它對 Cache 的處理邏輯。
回顧之前的簡單代碼,我們的入口是構造一個 Request 隊列,但並不直接 new,而是把控制權反轉給 Volley 這個靜態工廠來完成。
com.android.volley.toolbox.Volley:
public static RequestQueue newRequestQueue(Context context, HttpStack stack) {
File cacheDir = new File(context.getCacheDir(), DEFAULT_CACHE_DIR);
String userAgent = "volley/0";
try {
String packageName = context.getPackageName();
PackageInfo info = context.getPackageManager().getPackageInfo(packageName, 0);
userAgent = packageName + "/" + info.versionCode;
} catch (NameNotFoundException e) { }
if (stack == null) {
if (Build.VERSION.SDK_INT >= 9) {
stack = new HurlStack();
} else {
// Prior to Gingerbread, HttpUrlConnection was unreliable.
stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent));
}
}
Network network = new BasicNetwork(stack);
RequestQueue queue = new RequestQueue(new DiskBasedCache(cacheDir), network);
queue.start();
return queue;
}
參數 HttpStack 用於指定你的 Http 實現機制,比如採用 apache 的 http-client 還是 HttpUrlConnection。如果不指定,Volley 也會根據你的 SDK 版本給出不同策略。而這個 HttpStack 對象會被 Network 對象包裝起來。為了構造統一的網絡調用,Volley 通過橋接方式來實現,而橋接的接口就是 Network。
Volley 的核心在於 Cache 和 Network。兩個對象構造完畢後就能生成 RequestQueue。那為什麼要調用 queue.start() 呢?看這段代碼:
public void start() {
stop(); // Make sure any currently running dispatchers are stopped.
// Create the cache dispatcher and start it.
mCacheDispatcher = new CacheDispatcher(mCacheQueue, mNetworkQueue, mCache, mDelivery);
mCacheDispatcher.start();
// Create network dispatchers (and corresponding threads) up to the pool size.
for (int i = 0; i < mDispatchers.length; i++) {
NetworkDispatcher networkDispatcher = new NetworkDispatcher(mNetworkQueue, mNetwork, mCache, mDelivery);
mDispatchers[i] = networkDispatcher;
networkDispatcher.start();
}
}
Volley 採用生產者和消費者模式來產生反應堆,而這種反應必須通過線程來實現。調用 start() 之後,會開啟一個 Cache 線程和一定數量的 Network 線程池。NetworkDispatcher 的線程池數量由數組 mDispatchers 指定,而 mDispatchers 的賦值在 RequestQueue 的構造函數中:
public RequestQueue(Cache cache, Network network, int threadPoolSize, ResponseDelivery delivery) {
mCache = cache;
mNetwork = network;
mDispatchers = new NetworkDispatcher[threadPoolSize];
mDelivery = delivery;
}
到了 RequestQueue.start(),我們已經為 request 構建好了上下文環境,接下來只需要把它 add 到隊列裡:
public <T> Request<T> add(Request<T> request) {
request.setRequestQueue(this);
synchronized (mCurrentRequests) {
mCurrentRequests.add(request);
}
// Process requests in the order they are added.
request.setSequence(getSequenceNumber());
request.addMarker("add-to-queue");
// If the request is uncacheable, skip the cache queue and go straight to the network.
if (!request.shouldCache()) {
mNetworkQueue.add(request);
return request;
}
// Insert request into stage if there's already a request with the same cache key in flight.
synchronized (mWaitingRequests) {
String cacheKey = request.getCacheKey();
System.out.println("request.cacheKey = " + (cacheKey));
if (mWaitingRequests.containsKey(cacheKey)) {
// There is already a request in flight. Queue up.
Queue<Request<?>> stagedRequests = mWaitingRequests.get(cacheKey);
if (stagedRequests == null) {
stagedRequests = new LinkedList<Request<?>>();
}
stagedRequests.add(request);
mWaitingRequests.put(cacheKey, stagedRequests);
} else {
// Insert 'null' queue for this cacheKey, indicating there is now a request in flight.
mWaitingRequests.put(cacheKey, null);
mCacheQueue.add(request);
}
}
return request;
}
這段代碼中暫存(mWaitingRequests)的設計堪稱點睛之筆,它避免了重複請求。我們 add 一個 Request 時需要設置這個 RequestQueue,目的是為了結束時能把自己從 Queue 中回收。這裡還能看到一個簡單的狀態機:request.addMarker("add-to-queue"); 會在 request 不同的上下文中被調用,方便日後查錯。
之後 Request 會檢查是否需要 Cache:if (!request.shouldCache()) { mNetworkQueue.add(request); return request; }。在我們的觀念裡,文本數據似乎不需要 Cache,你可以通過這個方法來決定是否緩存你的數據,並不限制數據類型。如果請求不被暫存,那就被投入 Cache 反應堆。來看看 mCacheQueue:
private final PriorityBlockingQueue<Request<?>> mCacheQueue = new PriorityBlockingQueue<Request<?>>();
mCacheQueue 本質上是一個線程安全的 PriorityBlockingQueue,而且隊列裡可以進行優先級比較。ImageRequest 就對優先級做了指定:
@Override
public Priority getPriority() {
return Priority.LOW;
}
你也可以自己指定 Request 的優先級別。
回到 CacheDispatcher 消費者,它繼承自 Thread,生成後直接對 Cache 初始化 mCache.initialize(),目的是獲得 Cache 中已經存在的數據。Cache 的實現類是 DiskBasedCache.java,看看它如何初始化:
@Override
public synchronized void initialize() {
if (!mRootDirectory.exists()) {
if (!mRootDirectory.mkdirs()) {
VolleyLog.e("Unable to create cache dir %s", mRootDirectory.getAbsolutePath());
}
return;
}
File[] files = mRootDirectory.listFiles();
if (files == null) {
return;
}
for (File file : files) {
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
CacheHeader entry = CacheHeader.readHeader(fis);
entry.size = file.length();
putEntry(entry.key, entry);
} catch (IOException e) {
if (file != null) {
file.delete();
}
} finally {
try {
if (fis != null) {
fis.close();
}
} catch (IOException ignored) { }
}
}
}
由此可見,Volley 有別於其他 Cache 的一個特點:它會存儲元數據,或者說自定義了數據格式,在文件頭部增加了 Volley 的文件頭。這種做法不僅在某方面保證了數據的安全性,也能很好地存儲數據元。
public static CacheHeader readHeader(InputStream is) throws IOException {
CacheHeader entry = new CacheHeader();
int magic = readInt(is);
if (magic != CACHE_MAGIC) {
// don't bother deleting, it'll get pruned eventually
throw new IOException();
}
entry.key = readString(is);
entry.etag = readString(is);
if (entry.etag.equals("")) {
entry.etag = null;
}
entry.serverDate = readLong(is);
entry.ttl = readLong(is);
entry.softTtl = readLong(is);
entry.responseHeaders = readStringStringMap(is);
return entry;
}
從這段代碼能看到不少信息:Volley 自定義了自己的數據魔數(magic number),並按照自訂規範來讀取元數據。
初始化完成後,就轮到 CacheDispatcher 的核心邏輯了:
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);
response.intermediate = true;
mDelivery.postResponse(request, response, new Runnable() {
@Override
public void run() {
try {
mNetworkQueue.put(request);
} catch (InterruptedException e) { }
}
});
}
} catch (InterruptedException e) {
if (mQuit) {
return;
}
continue;
}
}
線程通過 while(true) 進行輪詢,由於 queue 是阻塞的,因此不會造成費電問題。
Cache.Entry entry = mCache.get(request.getCacheKey()); 獲取數據時,如果數據存在,會把真實數據讀取出來,這就是 Volley 的 LazyLoad(延遲加載)。
if (entry.isExpired()) 這段從時效性判斷是否進行淘汰。回顧前面的代碼,request 在不同上下文中總被標記為不同的狀態,這對後期維護有極其重要的意義。同時,為了保證接口的統一性,CacheDispatcher 會把自己的結果偽裝成 NetResponse——這樣對外部接口來說,無論採用哪種方式獲取數據,都當作網絡獲取來處理,這本身也是 DAO 模式存在的意義之一。
request.addMarker("cache-hit");
Response<?> response = request.parseNetworkResponse(
new NetworkResponse(entry.data, entry.responseHeaders));
request.addMarker("cache-hit-parsed");
request.parseNetworkResponse 的目的是讓 request 轉成自己的數據對象。到現在,對 Cache 來說就差分發了,數據已完全準備就緒。
Request 最終會拋給 Delivery 對象用來異步分發,這樣能有效避免分發造成的線程阻塞。Cache 會偽裝成 NetResponse 來 post 數據,也就是說對 Network 的處理這些部分也是一模一樣的。Volley 中 Delivery 的實現類是:
com.android.volley.ExecutorDelivery.java
public ExecutorDelivery(final Handler handler) {
// Make an Executor that just wraps the handler.
mResponsePoster = new Executor() {
@Override
public void execute(Runnable command) {
handler.post(command);
}
};
}
在構造函數中傳入了一個 Handler,如果這個 Handler 是 UI 線程的 Handler,那麼你的線程就是在 UI 線程中運行,避免了你自己 post UI 線程消息的麻煩。post 出來的數據會被封裝成 ResponseDeliveryRunnable 命令,這種命令跑在 Handler 所在的線程中。到此 CacheDispatcher 的基本流程就結束了,ResponseDeliveryRunnable 中除了分發以外也會做一些收尾工作,感興趣的讀者可以自己閱讀源碼。
深入解析 JavaScript 與 Android、iOS 原生控件的雙向通信
提到「熱更新」與「熱部署」,做混合式開發的朋友應該都不陌生。它要解決的問題其實很現實:App 每次升級都得走一遍應用商店,實在太笨重。電商類產品尤其忌諱這一點——不可能每
Android Activity 之間的資料傳遞:Intent 用法全解(附人品計算器實作)
本文用一個「人品計算器」小專案,把 Activity 之間傳遞資料的常見做法完整跑一遍:首頁輸入姓名,按下按鈕後跳到結果頁,由結果頁隨機算出一個人品值並顯示出來。 In
適配器模式在 Android 中的實作:把購物車接進商品中心
適配器模式(Adapter)屬於結構型模式,作用是把一個類的介面轉換成客戶端期待的另外一種介面,讓原本因為介面不相容而無法協同工作的兩個類能夠合作。它分成「類適配器」(繼
一次搞懂 Android 介面適配:從單位換算到 .9 圖的實戰筆記
為什麼 Android 一定要談適配 答案很直接:碎片化。海外統計機構 OpenSignal 曾公布過多份裝置調查,把去年 8 月的數據攤開來看會更清楚——裝置型號多、品