Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

从源码读懂 Volley:一条网络请求的完整生命历程

編輯:Android 開發實例

经过前三篇的学习,Volley 的用法我们已经掌握得差不多了,但它内部到底是怎么运转的,恐怕还有很多人说不上来。这一篇我们就直接读源码,把整条工作流程从头到尾梳理一遍。这也是 Volley 系列的最后一篇。

Volley 官方文档里本来就附了一张工作流程图:


 

没有概念基础就直接看这张图,大概只会一头雾水。没关系,先把源码走一遍,回头再看这张图会轻松很多。

从哪里开始读

回想一下 Volley 的用法:第一步总是调用 Volley.newRequestQueue(context) 拿一个 RequestQueue,那我们就从这里切入。

public static RequestQueue newRequestQueue(Context context) {
    return newRequestQueue(context, null);
}

只有一行,转调双参数版本并把第二個参数填成 null。看双参数版本:

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 {
            stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent));
        }
    }
    Network network = new BasicNetwork(stack);
    RequestQueue queue = new RequestQueue(new DiskBasedCache(cacheDir), network);
    queue.start();
    return queue;
}

第 10 行判断 stack 是否为 null,是的话就得自己造一个 HttpStack:系统版本号大于等于 9 用 HurlStack,否则用 HttpClientStack。两者的差别在实现底层——HurlStack 内部走 HttpURLConnection,HttpClientStack 内部走 HttpClient。至于为什么要这样按版本分流,可以参考我之前翻译的一篇文章:https://www.fengfly.com/plus/view-215110-1.html。

HttpStack 备好后,接着用它造出一个 Network 物件(负责实际处理网络请求),然后 new 出 RequestQueue,调用 start() 启动,最后把它回传。newRequestQueue() 的职责就到此为止。

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

先造一个 CacheDispatcher 并启动,再用 for 循环造出若干 NetworkDispatcher 并各自启动。CacheDispatcher 与 NetworkDispatcher 都继承自 Thread,而预设循环执行四次——也就是说,光是调用一次 Volley.newRequestQueue(context),后台就有五条线程在跑,持续等待网络请求到来。其中一条是缓存线程,四条是网络线程。

add():这条请求该进哪个队伍

拿到 RequestQueue 之后,构造好 Request 并调用 add() 就算完成一次网络请求。add() 内部的逻辑值得细看:

public <T> Request<T> add(Request<T> request) {
    // Tag the request as belonging to this queue and add it to the set of current requests.
    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();
        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;
    }
}

第 11 行先判断这条请求能不能缓存:不能缓存就直接扔进网络请求队列(第 12 行);可以缓存则进入第 33 行,加入缓存队列。Volley 预设每条请求都可以缓存,想改变这个行为就调用 setShouldCache(false)。

另外注意 mWaitingRequests 这段:如果同一个 cacheKey 已经有一条请求在处理中,后来的请求会先被暂存起来,等前一条有了结果再一起处理,避免对同一份资源发出重复请求。

CacheDispatcher:命中就到此为止

请求进了缓存队列,一直在后台待命的缓存线程就醒过来了。看 CacheDispatcher.run() 的重点段落:

@Override
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 (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: deliver the cached response, but also refresh from network.
                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;
        }
    }
}

几个判断依序是:第 11 行的 while(true) 说明缓存线程永远在跑;第 23 行尝试从缓存取出结果,取不到(cache miss)就把请求丢给网络队列;取到了但已完全过期,同样丢给网络队列;只有取到且未过期,才认为不必发网络请求,直接在第 39 行用 parseNetworkResponse() 解析缓存数据。

还有一种中间状态值得注意:refreshNeeded() 为真代表「软过期」。此时 Volley 会先把缓存内容当成 intermediate response 回给调用方,让界面立刻有东西可显示,同时再把请求送进网络队列去更新——这就是 Volley 能做到「先出旧数据、再换新数据」的机制。

NetworkDispatcher:真正发出请求的地方

@Override
public void run() {
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
    Request<?> request;
    while (true) {
        try {
            request = mQueue.take();
        } catch (InterruptedException e) {
            if (mQuit) {
                return;
            }
            continue;
        }
        try {
            request.addMarker("network-queue-take");
            if (request.isCanceled()) {
                request.finish("network-discard-cancelled");
                continue;
            }
            addTrafficStatsTag(request);
            // Perform the network request.
            NetworkResponse networkResponse = mNetwork.performRequest(request);
            request.addMarker("network-http-complete");
            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));
        }
    }
}

同样是 while(true)(第 7 行),网络线程也永不停歇。第 28 行调用 Network 的 performRequest() 发出真正的请求。Network 是个介面,实作是 BasicNetwork:

@Override
public NetworkResponse performRequest(Request<?> request) throws VolleyError {
    long requestStart = SystemClock.elapsedRealtime();
    while (true) {
        HttpResponse httpResponse = null;
        byte[] responseContents = null;
        Map<String, String> responseHeaders = new HashMap<String, String>();
        try {
            // Gather headers.
            Map<String, String> headers = new HashMap<String, String>();
            addCacheHeaders(headers, request.getCacheEntry());
            httpResponse = mHttpStack.performRequest(request, headers);
            StatusLine statusLine = httpResponse.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            responseHeaders = convertHeaders(httpResponse.getAllHeaders());
            // Handle cache validation.
            if (statusCode == HttpStatus.SC_NOT_MODIFIED) {
                return new NetworkResponse(HttpStatus.SC_NOT_MODIFIED,
                        request.getCacheEntry() == null ? null : request.getCacheEntry().data,
                        responseHeaders, true);
            }
            // Some responses such as 204s do not have content. We must check.
            if (httpResponse.getEntity() != null) {
                responseContents = entityToBytes(httpResponse.getEntity());
            } else {
                responseContents = new byte[0];
            }
            long requestLifetime = SystemClock.elapsedRealtime() - requestStart;
            logSlowRequests(requestLifetime, request, responseContents, statusLine);
            if (statusCode < 200 || statusCode > 299) {
                throw new IOException();
            }
            return new NetworkResponse(statusCode, responseContents, responseHeaders, false);
        } catch (Exception e) {
            ......
        }
    }
}

这段大多是 HTTP 细节,不用太在意。重点在第 14 行调用 HttpStack 的 performRequest()——这里的 HttpStack 就是一开始 newRequestQueue() 造出来的那个实例,内部实际由 HttpURLConnection 或 HttpClient 送出请求,随后把服务器回传的内容组装成 NetworkResponse 回传。顺带一提,服务器回 304 时 Volley 会直接复用缓存里的资料,不再重复回传一次相同内容。

解析与回调:交回主线程

NetworkDispatcher 拿到 NetworkResponse 后,会调用 Request 的 parseNetworkResponse() 解析数据并写入缓存。这个方法交由 Request 的子类实作——不同种类的 Request 解析方式本来就不一样。回想上一篇讲的自定义 Request,parseNetworkResponse() 正是必须覆写的方法之一。

解析完成后,ExecutorDelivery 的 postResponse() 负责把结果回调出去:

public void postResponse(Request<?> request, Response<?> response, Runnable runnable) {
    request.markDelivered();
    request.addMarker("post-response");
    mResponsePoster.execute(new ResponseDeliveryRunnable(request, response, runnable));
}

丢给 mResponsePoster.execute() 的是一个 ResponseDeliveryRunnable,它的 run() 保证在主线程执行:

@Override
public void run() {
    // If this request has canceled, finish it and don't deliver.
    if (mRequest.isCanceled()) {
        mRequest.finish("canceled-at-delivery");
        return;
    }
    // Deliver a normal response or error, depending.
    if (mResponse.isSuccess()) {
        mRequest.deliverResponse(mResponse.result);
    } else {
        mRequest.deliverError(mResponse.error);
    }
    // If this is an intermediate response, add a marker; otherwise we're done.
    if (mResponse.intermediate) {
        mRequest.addMarker("intermediate-response");
    } else {
        mRequest.finish("done");
    }
    if (mRunnable != null) {
        mRunnable.run();
    }
}

第 22 行的 deliverResponse() 是不是有点眼熟?没错,这就是我们自定义 Request 时必须覆写的另一个方法。每条请求的响应最后都会回到这里,我们再从中把数据交给 Response.Listener 的 onResponse(),一次请求的旅程就结束了。

回头看那张流程图

现在再回头看开头那张图:蓝色是主线程,绿色是缓存线程,橙色是网络线程。我们在主线程调用 RequestQueue 的 add() 送出请求,请求先进入缓存队列;命中就直接读取、解析、回调主线程;未命中或已过期,则转入网络请求队列,走完「发 HTTP 请求 → 解析响应 → 写入缓存 → 回调主线程」这条路径。

把这张图与源码对照起来,Volley 的设计意图就相当清楚了:用少量常驻线程加上两级队列,把「缓存优先、网络兜底」这件事做得既透明又便宜。到这里,Volley 的用法与源码就算全部走完了,把它放进实际專案里应该不成问题。

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