Volley使用总结及源码分析(二)

前提

上一次讲了Volley的核心RequestQueue,如果没有看过的话请参看Volley使用总结及源码分析(一),在其start方法中,维护了五个线程,一个缓存线程和四个网络线程,下面我们继续分析,在上一次提到注意线程初始化的时候传入的参数,那参数传入之后到底做了什么操作?

缓存线程

public class CacheDispatcher extends Thread {
    private static final boolean DEBUG = VolleyLog.DEBUG;
    private final BlockingQueue> mCacheQueue;
    private final BlockingQueue> mNetworkQueue;
    private final Cache mCache;
    private final ResponseDelivery mDelivery;
    private volatile boolean mQuit = false;
    public CacheDispatcher(
            BlockingQueue> cacheQueue, BlockingQueue> networkQueue,
            Cache cache, ResponseDelivery delivery) {
        //缓存请求队列
        mCacheQueue = cacheQueue;
        //网络请求队列
        mNetworkQueue = networkQueue;
        //DiskBasedCache类具体对象,用于本地缓存
        mCache = cache;
        //将响应传递回主线程
        mDelivery = delivery;
    }
    //退出线程
    public void quit() {
        mQuit = true;
        interrupt();
    }
    @Override
    public void run() {
        if (DEBUG) VolleyLog.v("start new dispatcher");      Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
        //初始化缓存
        mCache.initialize();
        while (true) {
            try {
                final Request request = mCacheQueue.take();
                request.addMarker("cache-queue-take");
                //判断是否取消
                if (request.isCanceled()) {
                    request.finish("cache-discard-canceled");
                    continue;
                }
                //当前请求是否有缓存,
                Cache.Entry entry = mCache.get(request.getCacheKey());
                if (entry == null) {
                    request.addMarker("cache-miss");
                    //没有缓存,加入到网络请求队列
                    mNetworkQueue.put(request);
                    continue;
                }
                //判断缓存是否过期
                if (entry.isExpired()) {
                    request.addMarker("cache-hit-expired");
                    request.setCacheEntry(entry);
                    //过期的话重新加入网络请求队列
                    mNetworkQueue.put(request);
                    continue;
                }
                //缓存没有过期的话,解析缓存为请求的响应
                request.addMarker("cache-hit");
                Response response = request.parseNetworkResponse(
                        new NetworkResponse(entry.data, entry.responseHeaders));
                request.addMarker("cache-hit-parsed");
                //原始数据源是否需要刷新
                if (!entry.refreshNeeded()) {
                 //将解析后的响应使用Delivery分发
                  mDelivery.postResponse(request, response);
                } else {
                  //重新请求网络,刷新缓存
                  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) {
                                // 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;
            }
        }
    }
}

 代码中加了中文注释,可以看到CacheDispatcher继承了Thread,实现了run方法。构造方法将传入的四个参数保存在成员变量中,quit方法设置取消标志,中断线程。run方法中首先对mCache进行初始化,然后不断从缓存请求队列中取请求处理mCacheQueue.take();,队列为空则等待,请求处理结束则将结果传递给ResponseDelivery 去执行后续处理。当结果未缓存过、缓存失效或缓存需要刷新的情况下,该请求都需要重新进入NetworkDispatcher去调度处理。

网络线程

public class NetworkDispatcher extends Thread {
    private final BlockingQueue> mQueue;
    private final Network mNetwork;
    private final Cache mCache;
    private final ResponseDelivery mDelivery;
    private volatile boolean mQuit = false;
    public NetworkDispatcher(BlockingQueue> queue,
            Network network, Cache cache,
            ResponseDelivery delivery) {
        //网络请求队列
        mQueue = queue;
        //具体执行网络交互
        mNetwork = network;
        //DiskBasedCache类具体对象,用于本地缓存
        mCache = cache;
         //将响应传递回主线程
        mDelivery = delivery;
    }
    public void quit() {
        mQuit = true;
        interrupt();
    }
    @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    private void addTrafficStatsTag(Request request) {
        // Tag the request (if API >= 14)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
           TrafficStats.setThreadStatsTag(request.getTrafficStatsTag());
        }
    }
    @Override
    public void run() {
        //设置线程优先级
        Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
        while (true) {
            //记录开始时间
            long startTimeMs = SystemClock.elapsedRealtime();
            Request request;
            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);
                //performRequest中,调用HttpStack处理请求
                NetworkResponse networkResponse = mNetwork.performRequest(request);
                request.addMarker("network-http-complete");
                if (networkResponse.notModified && request.hasHadResponseDelivered()) {
                    request.finish("not-modified");
                    continue;
                }
                //使用request的parseNetworkResponse方法解析,请求的网络响应
                Response response = request.parseNetworkResponse(networkResponse);
                request.addMarker("network-parse-complete");
                if (request.shouldCache() && response.cacheEntry != null) {
                    //添加缓存
                    mCache.put(request.getCacheKey(), response.cacheEntry);
                    request.addMarker("network-cache-written");
                }
                request.markDelivered();
                //将解析后的响应使用Delivery分发
                mDelivery.postResponse(request, response);
            } catch (VolleyError volleyError) {volleyError.setNetworkTimeMs(SystemClock.elapsedRealtime() - startTimeMs);
                parseAndDeliverNetworkError(request, volleyError);
            } catch (Exception e) {
                VolleyLog.e(e, "Unhandled exception %s", e.toString());
                VolleyError volleyError = new VolleyError(e);
                volleyError.setNetworkTimeMs(SystemClock.elapsedRealtime() - startTimeMs);
                mDelivery.postError(request, volleyError);
            }
        }
    }
    private void parseAndDeliverNetworkError(Request request, VolleyError error) {
        error = request.parseNetworkError(error);
        mDelivery.postError(request, error);
    }
}

 可以看到NetworkDispatcherCacheDispatcher很像,主要是run方法中的流程不同。设置线程优先级,不断从网络请求队列中取出网络请求,调用BasicNetwork中的performRequest方法处理请求,在该方法中调用HttpStack处理请求,并将结果转换为可被ResponseDelivery处理的NetworkResponse。使用request.parseNetworkResponse处理网络返回的响应,加入缓存,返回处理后的响应结果。

总结

 默认情况下,所有请求都会经过缓存线程判断,如果存在缓存且没有过期,则直接返回缓存的响应,否则加入网络线程中,在网络线程中,会调用HttpStack处理请求,返回的响应使用request的parseNetworkResponse方法进一步进行解析,并将结果缓存到本地。

你可能感兴趣的:(Volley使用总结及源码分析(二))