Volley为我们提供了非常简便了HTTP通信方式,那么这个框架内部是怎么运行的呢?让我们一步一步来分析。
整个Volley的运行分为了三类线程,分别为程序主线程,缓存处理线程和网络请求线程。主线程发出网络请求后,该请求先回被判断是否已在缓存队列中存在,若存在则直接在缓存队列中取出病返回数据,如若不存在则放入网络请求队列中等待处理。框架图在文末给出。
首先,看Volley.newRequestQueue(getApplicationContext());这是我们使用Volley 需要的第一行代码。在源码Volley.java中,
public static RequestQueue newRequestQueue(Context context) {
return newRequestQueue(context, null);//
}
此处实则调用了newRequestQueue(context, 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) {安卓版本大于2.3
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;
}
从12行到18行可以看到,根据android版本分别取创建HurlStack() 和HttpClientStack 。这两种方式分别去实现了httpurlconnection和httpClient 进行网络连接的方法。然而由于httpClient在6.0后被抛弃,因此需要判断安卓版本。
24行中new 了一个queue 之后便start 了,从这就要开始进入整个volley 的运行了。在RequestQueue.java中,
public RequestQueue(Cache cache, Network network) {
this(cache, network, DEFAULT_NETWORK_THREAD_POOL_SIZE);
}
第2行看到有个默认网络线程池,这个的大小是4,private static final int DEFAULT_NETWORK_THREAD_POOL_SIZE = 4;重要的是queue 开始start 后 进行了什么。
public void start() {
this.stop();
this.mCacheDispatcher = new CacheDispatcher(this.mCacheQueue, this.mNetworkQueue, this.mCache, this.mDelivery);
this.mCacheDispatcher.start();
for(int i = 0; i < this.mDispatchers.length; ++i) {
NetworkDispatcher networkDispatcher = new NetworkDispatcher(this.mNetworkQueue, this.mNetwork, this.mCache, this.mDelivery);
this.mDispatchers[i] = networkDispatcher;
networkDispatcher.start();
}
}
可以看见在第4行和第9行开始了缓存队列调度和网络请求队列调度。
mDispatchers = new NetworkDispatcher[threadPoolSize]; 之前说到threadPoolSize的大小为4 ,因此这里有4个网络调度线程同时启动。
现在先来看看缓存队列线程和网络请求线程的具体工作室什么。
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 the request has been canceled, don't bother dispatching it.
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. We can deliver the cached response,
// but we need to also send the request to the network for
// refreshing.
request.addMarker("cache-hit-refresh-needed");
request.setCacheEntry(entry);
// Mark the response as intermediate.
response.intermediate = true;
// Post the intermediate response back to the user and have
// the delivery then forward the request along to the network.
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;
}
在缓存线程中,通过读缓存队列的循环遍历,取出每一个request,经过是否被取消,判空,过期判断后,根据判断结果来返回数据或者将请求交给网络线程处理。接下来看看网络处理线程。
public void run() {
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);//设置线程优先级
while (true) {
long startTimeMs = SystemClock.elapsedRealtime();
Request<?> request;
try {
// Take a request from the queue.
request = mQueue.take();//从队列里面取出request
} catch (InterruptedException e) {
// We may have been interrupted because it was time to quit.
if (mQuit) {
return;
}
continue;
}
try {
request.addMarker("network-queue-take");
// If the request was cancelled already, do not perform the
// network request.
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 the server returned 304 AND we delivered a response already,
// we're done -- don't deliver a second identical response. //返回码304
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.
// TODO: Only update cache metadata instead of entire record for 304s.
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) {
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);
}
}
在网络请求线程中,也是通过先取出request 然后经过判空,再去执行请求。执行的代码mNetwork.performRequest(request); Network是一个接口,由BasicNetwork进行了实现。在performRequest中,通过HttpStack的实现类 实现了他的performRequest(request) 方法。接下来将返回结果进行解析,之后根据判断结果写入缓存队列,最后将结果返回主线程。因此到这,网络请求线程结束。
综上,整个Volley的运行分为了三大类线程。主线程,缓存调度线程以及网络通信线程。其中缓存调度线程负责从缓存队列中取出请求,经过一系列判断后来决定将该请求加入到网络通信请求队列中还是直接返回数据。而网络通信调度线程主要负责从网络通信请求队列中获取请求,再通过HTTP通信来获取数据,并且在网络通信线程一共新建了4条线程来进行通信工作。(图传不上来,有需要的同学可以自行百度Volley框架图)