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

Volley 源碼剖析(二):深入 Cache 緩存機制

編輯:關於 Android 程式設計

Cache 是 Volley 最核心的組成部分之一,Volley 在這上面花了不少心思。本文順著 Volley 的源碼脈絡,帶你看清楚它對 Cache 的處理邏輯。

從 RequestQueue 的構造說起

回顧之前的簡單代碼,我們的入口是構造一個 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 的優先級別。

Cache 的初始化:自定義數據格式

回到 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 的核心循環

初始化完成後,就轮到 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 來說就差分發了,數據已完全準備就緒。

異步分發:ExecutorDelivery

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 中除了分發以外也會做一些收尾工作,感興趣的讀者可以自己閱讀源碼。

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