Volley是个轻量级的通信框架,对Android开发来说确实比较好用,扩展性也强。不过今天谈的不是它的应用,而是剖析它的一个问题,就是Volley使用缓存,则会响应3次。这篇文章的思路只讲最核心的代码,其他代码就不贴了,获取源码也简单的。
在Volley中有一个缓存线程,4个网络请求线程,分别为CacheDispatcher.java,NetworkDispatcher.java。
分析过程不按照调用顺序来讲,是从最重要的地方开始,然后再分析调用它的地方,这样带着问题来分析,可能更有意思。
在CacheDispatcher.java的run方法中,有如下代码:
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. 1 Cache.Entry entry = mCache.get(request.getCacheKey()); 2 if (entry == null) { request.addMarker("cache-miss"); // Cache miss; send off to the network dispatcher. 3 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"); 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. 4 mDelivery.postResponse(request, response, new Runnable() { @Override public void run() { try { 5 mNetworkQueue.put(request); } catch (InterruptedException e) { // Not much we can do about this. } } }); 6 mDelivery.postResponse(request, response);
有while(true),说明这个线程是一直运行着,在1处,从request中取出key对应的缓存Entry,key其实就是request的url,2处如果缓存为空,3处在将请求加入网络请求队列,continue,继续下一次循环(由NetworkDispatcher.java会处理这个请求)。这种情况不在讨论之内,在4处,mDelivery调用postResponse,看看里面怎么写的。mDelivery是ExecutorDelivery的实例。
@Override public void postResponse(Request<?> request, Response<?> response, Runnable runnable) { request.markDelivered(); request.addMarker("post-response"); 1 mResponsePoster.execute(new ResponseDeliveryRunnable(request, response, runnable)); }
在1处,则看看mResponsePoster的定义。
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); } }; }
可以看到mResponsePoster所要执行的任务,执行hanlder.post(commnad)后,任务是在主线程执行的,看看command的实现代码,挑它的run方法看
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()) { 1 mRequest.deliverResponse(mResponse.result); } else { 2 mRequest.deliverError(mResponse.error); } // If this is an intermediate response, add a marker, otherwise we're done // and the request can be finished. if (mResponse.intermediate) { mRequest.addMarker("intermediate-response"); } else { 3 mRequest.finish("done"); } // If we have been provided a post-delivery runnable, run it. if (mRunnable != null) { mRunnable.run(); } }
1处就是将结果返回,看看deliverResponse()的实现,继承Requst的类JsonRequest,看它的实现:
protected void deliverResponse(T response) { 1 mListener.onResponse(response); }
1处这个mListener的类型是Response.Listener,正好是我们定义request的时候传进去的,如
request = new JsonPostRequest(IMConfig.mUserSummary, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject jsonObject) { } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError volleyError) { } }, map);
这样流程完毕,就是响应了1次,第二次是怎么来的呢,回顾CacheDispatcher.java的5处,是将请求放到了网络请求队列中,网络线程NetworkDispatcher.java就会检测到这个请求,会执行网络操作,操作完成后,也会回到主线程响应,简要分析它的代码 run方法,如下
while (true) { try { // Take a request from the queue. request = mQueue.take(); } 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. 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) { 1 mCache.put(request.getCacheKey(), response.cacheEntry); request.addMarker("network-cache-written"); } // Post the response back. request.markDelivered(); 2 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)); } }
可以看到又是个死循环,从而网络队列里只要有request,一定会被执行到,其他地方不看,就看2处,通过前面的分析,清楚postResponse的逻辑是将结果返回到主线程响应,这就是第二次。第三次就看CacheDispatcher.java的run方法的6处,又发现调用了一次postResponse(),又将结果返回到主线程响应,到这里共有3次响应了,至于google的这个volley为什么要做3次,也觉得困惑,个人觉得第三次响应是没必要的。前面的分析有很多细节之处没有分析到位,就如同前面所说,只取这个问题的最核心的地方,其他细节之处可以看源码。
在最新的Volley的版本中,已把这个问题修复了,CacheDispatcher.java代码如下:
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"); 1 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; } }
看1处的代码,通过对实体判断需要更新的话,会再次请求网络,不更新的话,则直接响应。