Android中关于Volley的使用(五)从RequestQueue开始来深入认识Volley

在前面的几篇文章中,我们学习了如何用Volley去网络加载JSON数据,如何利用ImageRequest和NetworkImageView去网络加载数据,而关于Volley的使用,我们都是从下面一行代码开始的:

Volley.newRequestQueue(this);

这是Volley类创建了一个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.
     *
     * @param context A {@link Context} to use for creating the cache dir.
     * @return A started {@link RequestQueue} instance.
     */
    public static RequestQueue newRequestQueue(Context context) {
        return newRequestQueue(context, null);
    }
}

Volley类只有两个方法,而主要的创建RequestQueue的方法就是包含两个参数Context和HttpStack的newRequestQueue方法了,另外一个只是调用这个方法,将传一个null的HttpStack而已。

我们看看这个方法里面的实现:

    public static RequestQueue newRequestQueue(Context context, HttpStack stack) {
        File cacheDir = new File(context.getCacheDir(), DEFAULT_CACHE_DIR);//缓存文件

        String userAgent = "volley/0";//UserAgent用来封装应用的包名跟版本号,提供给服务器,就跟浏览器信息一样
        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();//SDK如果大于等于9,也就是Android 2.3以后,因为引进了HttpUrlConnection,所以会用一个HurlStack
            } else {//如果小于9,则是用HttpClient来实现
                // Prior to Gingerbread, HttpUrlConnection was unreliable.
                // See: http://android-developers.blogspot.com/2011/09/androids-http-clients.html
                stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent));
            }
        }

        Network network = new BasicNetwork(stack);//创建一个Network,构造函数需要一个stack参数,Network里面会调用stack去跟网络通信
	//创建RequestQueue,并将缓存实现DiskBasedCache和网络实现BasicNetwork传进去,然后调用start方法
        RequestQueue queue = new RequestQueue(new DiskBasedCache(cacheDir), network);
        queue.start();
       
        return queue;
    }
大家可以看代码中的注释,这里简要说明一下步骤:

1)创建缓存文件和UserAgenp字符串

2)根据SDK版本来创建HttpStack的实现,如果是2.3以上的,则使用基于HttpUrlConnection实现的HurlStack,反之,则利用HttpClient实现的HttpClientStack。

3)创建一个BasicNetwork对象,并将HttpStack封装在Network中

4)创建一个DiskBasedCache对象,和Network一起,传给RequestQueue作为参数,创建RequestQueue对象。

5)调用 RequestQueue的 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的实现
    }
在构造函数中,我们可以看到在Volley类中创建的Cache和Network。

另外,通过前面传进来的线程数量(默认是4),会创建一个NetworkDispatcher的数组,也就是创建了一个有4个线程的线程池,因为NetworkDispatcher是继承于Thread的实现类,其定义如下:

public class NetworkDispatcher extends Thread {
而delivery的实现则是ExecutorDelivery,我们可以看到它的参数是一个Handler,而Handler的构造函数参数则是Looper.getMainLooper(),这其实是应用的主线程的Looper,也就是说,Handler其实是主线程中的Hanlder,ExecutorDelivery的定义如下:

    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来将Response传回主线程进行UI更新,比如之前的更新ImageView,因为我们知道,UI的更新必须在主线程。

到这里,我们的RequestQueue对象就创建好了,下面就是要调用它的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();
            }
        }
    }

我们可以看到,

1)start方法的一开始,会先调用stop方法。stop会将缓存线程还有所有的网络线程停止。

2)重新创建一个缓存线程,并启动,在这里,会将 mCacheQueue,mNetwrok, mCache 和 mDelivery 传给其构造函数。

3)根据线程池的大小,创建相对应数目的网络线程,而在这里,我们可以看到会将 mNetworkQueue,mNetwrok,mCache 和 mDelivery作为参数传给NetworkDispatcher。

很明显,当调用RequestQueue的 start方法的时候,其实也就是启动了一个缓存线程和默认的4个网络线程,它们就会在后面静静地等待请求的到来。

在两个构造函数上面,mNetwork, mCache 和 mDelivery,我们上面都介绍过了,但是 mCacheQueue 和 mNetworkQueue,这两个具体是什么样的呢?

    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并发(Concurrent)包中提供的利用优先级来执行的阻塞队列PriorityBlockingQueue。显然,它们就应该是来放置从外面传进来的请求的,比如JsonRequest,ImageRequest和 StringRequest。

而RequestQueue类中,还有另外两个请求集合:

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

    //所有在队列中,或者正在被处理的请求都会在这个集合中
    private final Set<Request<?>> mCurrentRequests = new HashSet<Request<?>>();

我们记得,当我们创建好RequestQueue对象之后,如果我们想要去加载图片,我们就会创建ImageRequest对象,如果我们想要去获取Json数据,我们就会创建JsonRequest对象,而最后我们都会调用 RequestQueue的add方法,来将请求加入到队列中的。

    public <T> Request<T> add(Request<T> request) {
        // 将请求的队列设置为当前队列,并将请求添加到mCurrentRequests中,表明是正在处理中的,而在这里,我们可以看到利用synchronized来同步
        request.setRequestQueue(this);
        synchronized (mCurrentRequests) {
            mCurrentRequests.add(request);
        }

        // 在这里会设置序列号,保证每个请求都是按顺序被处理的。
        request.setSequence(getSequenceNumber());
        request.addMarker("add-to-queue");

        // 如果这个请求是设置不缓存的,那么就会将其添加到mNetworkQueue中,直接去网络中获取数据
        if (!request.shouldCache()) {
            mNetworkQueue.add(request);
            return request;
        }

        // 到这里,表明这个请求可以去先去缓存中获取数据。
        synchronized (mWaitingRequests) {
            String cacheKey = request.getCacheKey();
            if (mWaitingRequests.containsKey(cacheKey)) {//如果这个请求已经有一个相同的请求(相同的CacheKey)在mWatingRequest中,那么就要将相同CacheKey的请求用一个LinkedList给装起来,先不需要处理,等那个正在处理的请求结束后,再看看应该怎么处理。

                // 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);
                if (VolleyLog.DEBUG) {
                    VolleyLog.v("Request for cacheKey=%s is in flight, putting on hold.", cacheKey);
                }
            } else {
		//如果mWaitingRequest中没有,那么就将其添加到集合中,将添加到mCacheQueue队列中,表明现在这个cacheKey的请求已经在处理了。
                mWaitingRequests.put(cacheKey, null);
                mCacheQueue.add(request);
            }
            return request;
        }
    }
而当mCacheQueue或者mNetworkQueue利用add方法添加请求之后,在运行的线程就会接收到请求,从而去处理相对应的请求,最后将处理的结果由mDelivery来发送到主线程进行更新。

到这里,我们的请求就会在缓存线程或者网络线程中去处理了,当它们结束之后,每一个Request就会调用自身的finish方法,如下:

    void finish(final String tag) {
        if (mRequestQueue != null) {
            mRequestQueue.finish(this);
        }
而在这里,它调用的其实是 RequestQueue的finish方法,如下:

    void finish(Request<?> request) {
        // Remove from the set of requests currently being processed.
        synchronized (mCurrentRequests) {
            mCurrentRequests.remove(request);
        }

        if (request.shouldCache()) {
            synchronized (mWaitingRequests) {
                String cacheKey = request.getCacheKey();
                Queue<Request<?>> waitingRequests = mWaitingRequests.remove(cacheKey);
                if (waitingRequests != null) {
                    if (VolleyLog.DEBUG) {
                        VolleyLog.v("Releasing %d waiting requests for cacheKey=%s.",
                                waitingRequests.size(), cacheKey);
                    }
                    // Process all queued up requests. They won't be considered as in flight, but
                    // that's not a problem as the cache has been primed by 'request'.
                    mCacheQueue.addAll(waitingRequests);
                }
            }
        }
    }

可以看到,第一步就是将请求从mCurrentRequests中移除,正好对应了上面add方法中的添加。

第二步就是判断这个请求有没有缓存,如果有,那么我们这个时候,将前面mWaitingQueue中相同CacheKey的一大批请求再一股脑儿的扔到mCacheQueue中,为什么现在才扔呢?因为前面我们不知道相同CacheKey的那个请求到底在缓存中有没有,如果没有,它需要去网络中获取,那就等到它从网络中获取之后,放到缓存中后,它结束了,并且已经缓存了,这个时候,我们就可以保证后面那堆相同CacheKey的请求可以在缓存中去取到数据了,而不需要再去网络中获取了。

在RequestQueue中,还提供了两个方法去取消请求,如下:

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

    /**
     * Cancels all requests in this queue with the given tag. Tag must be non-null
     * and equality is by identity.
     */
    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;
            }
        });
    }

如上,第一个cancleAll会获取一个RequestFilter,这是RequestQueue的内部接口,定义如下:

    public interface RequestFilter {
        public boolean apply(Request<?> request);
    }
我们需要自己去实现,什么样的请求才是符合我们的过滤器的,然后在cancel中根据我们定义的过滤规则去批量地取消请求。

而第二个则是利用创建Request时设置的Tag值,实现RequestFilter,然后调用上一个cancelAll方法,来取消一批同个Tag值的请求。

这两个方法(其实是一种,主要是利用Tag来批量取消请求)跟我们这个流程的关系不大,所以就不在这里多讲了。

嗯,关于RequestQueue中一切,到这里,也就结束了,不知道讲得清不清楚,还希望大家多给点建议。

  • 5
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值