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

深入 Volley 核心:從 RequestQueue 建立過程看懂整個請求流程

編輯:關於 Android 程式設計

前面的文章談過如何用 Volley 載入 JSON 資料,以及用 ImageRequest、NetworkImageView 載入圖片。但不管做哪一種,我們的起點其實都是同一行:

Volley.newRequestQueue(this);

就是這行呼叫建立了 RequestQueue。Volley 的一切,都從這裡開始。接下來我們往裡頭鑽,看看這個方法背後到底做了什麼。

Volley 類只有兩個方法

public class Volley {
    ...
    public static RequestQueue newRequestQueue(Context context, HttpStack stack) {
        ...
    }

    /**
     * Creates a default instance of the worker pool and calls
     * {@link RequestQueue#start()} on it.
     */
    public static RequestQueue newRequestQueue(Context context) {
        return newRequestQueue(context, null);
    }
}

很明顯,對外暴露的無參數版本只是轉手呼叫雙參數版本,並把 HttpStack 傳成 null。真正的邏輯都在後者裡。

newRequestQueue 做了哪五件事

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) {
        // 一般我們不需要自己傳,Volley 會依 SDK 版本決定實作
        if (Build.VERSION.SDK_INT >= 9) {
            stack = new HurlStack();   // 2.3 以後引入 HttpUrlConnection
        } else {
            // Gingerbread 之前 HttpUrlConnection 不太可靠,改用 HttpClient
            stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent));
        }
    }

    Network network = new BasicNetwork(stack);  // 把 stack 封裝進 Network
    RequestQueue queue = new RequestQueue(new DiskBasedCache(cacheDir), network);
    queue.start();
    return queue;
}

濃縮成步驟:

  1. 建立緩存檔案與 UserAgent 字串。
  2. 依 SDK 版本選擇 HttpStack 實作:2.3 以上用 HurlStack(底層是 HttpUrlConnection),以下則用 HttpClientStack。
  3. 建立 BasicNetwork,並把 HttpStack 封裝進去。
  4. 建立 DiskBasedCache,與 Network 一起傳給 RequestQueue 的建構子。
  5. 呼叫 start() 啟動,回傳 queue。

RequestQueue 的三層建構子

public RequestQueue(Cache cache, Network network) {
    this(cache, network, DEFAULT_NETWORK_THREAD_POOL_SIZE); // 與網路互動的線程數,預設 4
}

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

public RequestQueue(Cache cache, Network network, int threadPoolSize, ResponseDelivery delivery) {
    mCache = cache;                                   // 緩存
    mNetwork = network;                               // 網路
    mDispatchers = new NetworkDispatcher[threadPoolSize]; // 線程池
    mDelivery = delivery;                             // Response 派送實作
}

兩個重點值得停留一下:

NetworkDispatcher 是 Thread 的子類(public class NetworkDispatcher extends Thread),所以那個陣列本質上就是四條等待中的執行緒。

ExecutorDelivery 收到的是主線程的 Handler。它的建構子參數是 new Handler(Looper.getMainLooper()),也就是應用程式主線程的 Looper:

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);
        }
    };
}

這解釋了一個常見疑問:為什麼用 Volley 更新 ImageView 不會出錯?因為結果最終是被 post 回主線程處理的,而 UI 更新本來就必須在主線程進行。

start():真正的引擎啟動點

public void start() {
    stop();  // 先確保所有執行中的 Dispatcher 都停下來

    // 建立緩存派發器(也是一條線程)並啟動
    mCacheDispatcher = new CacheDispatcher(mCacheQueue, mNetworkQueue, mCache, mDelivery);
    mCacheDispatcher.start();

    // 依線程池大小建立對應數量的 NetworkDispatcher 並全部啟動
    for (int i = 0; i < mDispatchers.length; i++) {
        NetworkDispatcher networkDispatcher =
                new NetworkDispatcher(mNetworkQueue, mNetwork, mCache, mDelivery);
        mDispatchers[i] = networkDispatcher;
        networkDispatcher.start();
    }
}

public void stop() {
    if (mCacheDispatcher != null) mCacheDispatcher.quit();
    for (int i = 0; i < mDispatchers.length; i++) {
        if (mDispatchers[i] != null) mDispatchers[i].quit();
    }
}

所以 start() 的效果就是:先停掉舊的,再啟動一條緩存線程加上預設四條網路線程,它們之後就靜靜地等請求送來。

兩個優先級佇列

private final PriorityBlockingQueue<Request<?>> mCacheQueue = new PriorityBlockingQueue<Request<?>>();

/** The queue of requests that are actually going out to the network. */
private final PriorityBlockingQueue<Request<?>> mNetworkQueue = new PriorityBlockingQueue<Request<?>>();

兩者都是 Java 並發套件中的優先級阻塞佇列,用來排隊等待處理的請求——JsonRequest、ImageRequest、StringRequest 都走這裡。優先級的意思是:每個 Request 都能設定 priority,讓關鍵請求插隊先跑。

此外還有兩個集合:

// 等待中的請求集合
private final Map<String, Queue<Request<?>>> mWaitingRequests = new HashMap<String, Queue<Request<?>>>();

// 所有在佇列中或正在處理的請求
private final Set<Request<?>> mCurrentRequests = new HashSet<Request<?>>();

add():請求是怎麼進場的

public <T> Request<T> add(Request<T> request) {
    // 綁定所屬佇列,並標記為處理中
    request.setRequestQueue(this);
    synchronized (mCurrentRequests) {
        mCurrentRequests.add(request);
    }

    // 設定序號,保證每個請求都有順序可依
    request.setSequence(getSequenceNumber());
    request.addMarker("add-to-queue");

    // 明確要求不快取的請求,直接進網路佇列
    if (!request.shouldCache()) {
        mNetworkQueue.add(request);
        return request;
    }

    // 走到這裡代表可以(也應該)先查緩存
    synchronized (mWaitingRequests) {
        String cacheKey = request.getCacheKey();
        if (mWaitingRequests.containsKey(cacheKey)) {
            // 已有相同 cacheKey 的請求在飛行中,先排隊等它
            Queue<Request<?>> stagedRequests = mWaitingRequests.get(cacheKey);
            if (stagedRequests == null) {
                stagedRequests = new LinkedList<Request<?>>();
            }
            stagedRequests.add(request);
            mWaitingRequests.put(cacheKey, stagedRequests);
        } else {
            // 沒有重複請求,登記後丟進緩存佇列
            mWaitingRequests.put(cacheKey, null);
            mCacheQueue.add(request);
        }
    }
    return request;
}

這段邏輯的巧妙之處在於去重:同一個 cacheKey 若已有請求在跑,後來者不會各自再去打一輪網路,而是掛在 mWaitingRequests 中等前一個的結果。

finish():請求退場

void finish(final String tag) {
    if (mRequestQueue != null) {
        mRequestQueue.finish(this);
    }
}

void finish(Request<?> request) {
    // 從處理中集合移除,正好對應 add() 的加入
    synchronized (mCurrentRequests) {
        mCurrentRequests.remove(request);
    }

    if (request.shouldCache()) {
        synchronized (mWaitingRequests) {
            String cacheKey = request.getCacheKey();
            Queue<Request<?>> waitingRequests = mWaitingRequests.remove(cacheKey);
            if (waitingRequests != null) {
                // 一次放行所有排隊的請求
                mCacheQueue.addAll(waitingRequests);
            }
        }
    }
}

為什麼要等到現在才放行?因為在這個請求結束之前,Volley 無從得知相同 cacheKey 的資料究竟在不在緩存裡。如果不在,它得親自跑一趟網路;等它取回並寫入緩存、宣告結束之後,後面那批同 cacheKey 的請求就能穩穩地從緩存讀到資料,不必再耗一次網路。這就是 Volley 節省流量的核心機制。

取消請求

public void cancelAll(RequestFilter filter) {
    synchronized (mCurrentRequests) {
        for (Request<?> request : mCurrentRequests) {
            if (filter.apply(request)) {
                request.cancel();
            }
        }
    }
}

public void cancelAll(final Object tag) {
    if (tag == null) {
        throw new IllegalArgumentException("Cannot cancelAll with a null tag");
    }
    cancelAll(new RequestFilter() {
        @Override
        public boolean apply(Request<?> request) {
            return request.getTag() == tag;
        }
    });
}

public interface RequestFilter {
    public boolean apply(Request<?> request);
}

第一個版本讓你自行實作過濾規則,第二個版本則是依建立 Request 時設定的 Tag 批次取消。實務上最常見的用法是「離開頁面時取消該頁面的所有請求」,避免回調打到已經銷毀的 Activity 而引發混亂。

整體圖像

把流程串起來就是:請求進入 → 先查緩存線程 → 命中就直接派送回主線程;未命中則轉交網路線程 → 取回後寫入緩存 → 透過 mDelivery 送回主線程更新 UI → finish 放行排隊中的同類請求。四條網路線程負責併發,一條緩存線程負責前置攔截,這就是 Volley 輕量又高效的秘密。

值得補充的是,Volley 官方早已停止更新,不適合再用於大型或長連線的場景(例如影音串流)。但它清晰的責任分工——佇列、快取、網路、派送——至今仍是理解 HTTP 客戶端設計最好的教材。

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