您的位置:首页 > 其它

Volley源码分析(1)----Volley 队列

2015-12-18 17:35 225 查看
Android网络框架很多,但是基于Google自己的volley,无疑是优秀的一款。

网络框架,无外乎解决一下几个问题,队列,缓存,图片异步加载,统一的网络请求和处理等。

一.Volley 队列 启动

Volley的队列,首先我们看队列的启动:com.android.volley.toolbox.Volley.java

/**
* 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.
* @param stack An {@link HttpStack} to use for the network, or null for default.
* @return A started {@link RequestQueue} instance.
*/
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.
// See: http://android-developers.blogspot.com/2011/09/androids-http-clients.html stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent));
}
}

Network network = new BasicNetwork(stack);

RequestQueue queue = new RequestQueue(new DiskBasedCache(cacheDir), network);
queue.start();

return queue;
}


我们依次分析这个方法。这个方法是队列启动的代码。

开始就是获取缓存文件夹,以及userAgent 一些信息。

Build.VERSION.SDK_INT >= 9

会使用HTTPURLConnection作为网络请求,而老的版本就使用httpclient来处理。

关于这2者的区别,很多地方有介绍。HttpUrlConnection是HttpClient轻量级版本。

应该说性能更好,并且足够android平台使用了。

当然,也可以使用自己定义的HttpStack。

Network network = new BasicNetwork(stack);


Network对stack的进一步封装,然后创建队列和启动队列。

com/android/volley/RequestQueue.java:

/**
* Starts the dispatchers in this queue.
*/
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();
}
}


启动队列,就是启动了一条cache thread 和4个 network thread。

然后分析CacheDispatcher 和NetworkDispatcher 这两个东东。

二:NetworkDispatcher

这一节我们分析网络请求,所以就忽略cache的部分,将在下一节分析:

public class NetworkDispatcher extends Thread


NetworkDispatcher是一个thread,可见network请求应该是从requestQueue队列中获取数据以后,已while(true)的形式不断的向服务器请求,

当requestQueue 为空时,线程讲block住,直到队列有数据,或者线程推出为止。

com/android/volley/NetworkDispatcher.java:

/**
* Adds a Request to the dispatch queue.
* @param request The request to service
* @return The passed-in request
*/
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);
if (VolleyLog.DEBUG) {
VolleyLog.v("Request for cacheKey=%s is in flight, putting on hold.", cacheKey);
}
} else {
// Insert 'null' queue for this cacheKey, indicating there is now a request in
// flight.
mWaitingRequests.put(cacheKey, null);
mCacheQueue.add(request);
}
return request;
}
}


add
private final Set<Request<?>> mCurrentRequests 这个集合用于记录当前正在队列里面的request,此处的集合应该是所有的request。

request.setSequence(getSequenceNumber());


用于request的排序。

if (!request.shouldCache()) {
mNetworkQueue.add(request);
return request;
}


request是否cache,如果否,讲直接放到network队列做请求操作。

// 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);
if (VolleyLog.DEBUG) {
VolleyLog.v("Request for cacheKey=%s is in flight, putting on hold.", cacheKey);
}
} else {
// Insert 'null' queue for this cacheKey, indicating there is now a request in
// flight.
mWaitingRequests.put(cacheKey, null);
mCacheQueue.add(request);
}
return request;
}


如果cache队列里面已经有正在处理的request,就无需放入cache队列,直接等待返回结果时,会把所有重复的request加入cache。

下面我们分析cache线程的情况。

我们已经说过,request会在网络请求结束的时候,把可以cache的request放入cache库中。

com/android/volley/CacheDispatcher.java

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


通过cachekey,获取缓存的数据。没有的话,将有network dispatcher来处理。

接下来判断是否过期。

过期有2中状态,软过期,和completely 过期。

completely 过期。直接请求网络。

软过期,先response到前台,然后后台进行更新。

这个就是cache线程在干的事情。

再看看刚才response时如何产生cache数据的。

// Parse the response here on the worker thread.
Response<?> response = request.parseNetworkResponse(networkResponse);


可以看到居然是由每个request自己来决定如何产生cache数据。

Cache.Entry的获得将在:

com/android/volley/toolbox/HttpHeaderParser.java:

public static Cache.Entry parseCacheHeaders(NetworkResponse response)


中获得。这个方法时公共的,如何以后有自定义请求的时候,可以使用该方法。

自此一个volley的队列已经搭载启动了。

我们只需要把request放入requestQueue就可以了!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: