Android網路程式設計(四)從原始碼解析Volley

weixin_34007886發表於2016-07-31

1.Volley結構圖

1417629-885d36708b563916

從上圖可以看到Volley分為三個執行緒,分別是主執行緒、快取排程執行緒、和網路排程執行緒,首先請求會加入快取佇列,如果發現可以找到相應的快取結果就直接讀取快取並解析,然後回撥給主執行緒;如果在快取中沒有找到結果,則將這條請求加入到網路佇列中,然後傳送HTTP請求,解析響應並寫入快取,並回撥給主執行緒。

2.從RequestQueue入手

我們都知道使用Volley之前首先要建立RequestQueue:

 RequestQueue mQueue = Volley.newRequestQueue(getApplicationContext());

這也是volley運作的入口,看看newRequestQueue:

 public static RequestQueue newRequestQueue(Context context) {
        return newRequestQueue(context, (HttpStack)null);
    }

public static RequestQueue newRequestQueue(Context context, HttpStack stack) {
        return newRequestQueue(context, stack, -1);
    }

連續呼叫了兩個過載函式,最終呼叫的是:

public static RequestQueue newRequestQueue(Context context, HttpStack stack, int maxDiskCacheBytes) {
        File cacheDir = new File(context.getCacheDir(), "volley");
        String userAgent = "volley/0";

        try {
            String network = context.getPackageName();
            PackageInfo queue = context.getPackageManager().getPackageInfo(network, 0);
            userAgent = network + "/" + queue.versionCode;
        } catch (NameNotFoundException var7) {
            ;
        }

        if(stack == null) {
            if(VERSION.SDK_INT >= 9) {
                stack = new HurlStack();
            } else {
                stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent));
            }
        }

        BasicNetwork network1 = new BasicNetwork((HttpStack)stack);
        RequestQueue queue1;
        if(maxDiskCacheBytes <= -1) {
            queue1 = new RequestQueue(new DiskBasedCache(cacheDir), network1);
        } else {
            queue1 = new RequestQueue(new DiskBasedCache(cacheDir, maxDiskCacheBytes), network1);
        }

        queue1.start();
        return queue1;
    }

可以看到如果android版本大於等於2.3則呼叫基於HttpURLConnection的HurlStack,否則就呼叫基於HttpClient的HttpClientStack。並建立了RequestQueue,呼叫了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();
        }

    }

CacheDispatcher是快取排程執行緒,並呼叫了start()方法,在迴圈中呼叫了NetworkDispatcher的start()方法,NetworkDispatcher是網路排程執行緒,預設情況下mDispatchers.length為4,預設開啟了4個網路排程執行緒,也就是說有5個執行緒在後臺執行並等待請求的到來。接下來我們建立各種的Request,並呼叫RequestQueue的add()方法:

 public <T> Request<T> add(Request<T> request) {
        request.setRequestQueue(this);
        Set var2 = this.mCurrentRequests;
        synchronized(this.mCurrentRequests) {
            this.mCurrentRequests.add(request);
        }

        request.setSequence(this.getSequenceNumber());
        request.addMarker("add-to-queue");
        //如果不能快取,則將請求新增到網路請求佇列中
        if(!request.shouldCache()) {
            this.mNetworkQueue.add(request);
            return request;
        } else {
            Map var8 = this.mWaitingRequests;
            synchronized(this.mWaitingRequests) {
                String cacheKey = request.getCacheKey();
        
       //之前是否有執行相同的請求且還沒有返回結果的,如果有的話將此請求加入mWaitingRequests佇列,不再重複請求
                if(this.mWaitingRequests.containsKey(cacheKey)) {
                    Object stagedRequests = (Queue)this.mWaitingRequests.get(cacheKey);
                    if(stagedRequests == null) {
                        stagedRequests = new LinkedList();
                    }

                    ((Queue)stagedRequests).add(request);
                    this.mWaitingRequests.put(cacheKey, stagedRequests);
                    if(VolleyLog.DEBUG) {
                        VolleyLog.v("Request for cacheKey=%s is in flight, putting on hold.", new Object[]{cacheKey});
                    }
                } else {
   //沒有的話就將請求加入快取佇列mCacheQueue,同時加入mWaitingRequests中用來做下次同樣請求來時的重複判斷依據
                    this.mWaitingRequests.put(cacheKey, (Object)null);
                    this.mCacheQueue.add(request);
                }

                return request;
            }
        }
    }

通過判斷request.shouldCache(),來判斷是否可以快取,預設是可以快取的,如果不能快取,則將請求新增到網路請求佇列中,如果能快取就判斷之前是否有執行相同的請求且還沒有返回結果的,如果有的話將此請求加入mWaitingRequests佇列,不再重複請求;沒有的話就將請求加入快取佇列mCacheQueue,同時加入mWaitingRequests中用來做下次同樣請求來時的重複判斷依據。
從上面可以看出RequestQueue的add()方法並沒有做什麼請求網路或者對快取進行操作。當將請求新增到網路請求佇列或者快取佇列時,這時在後臺的網路排程執行緒和快取排程執行緒輪詢各自的請求佇列發現有請求任務則開始執行,我們先看看快取排程執行緒。

3.CacheDispatcher快取排程執行緒

CacheDispatcher的run()方法:

    public void run() {
        if(DEBUG) {
            VolleyLog.v("start new dispatcher", new Object[0]);
        }
        //執行緒優先順序設定為最高階別
        Process.setThreadPriority(10);
        this.mCache.initialize();

        while(true) {
            while(true) {
                while(true) {
                    while(true) {
                        try {
                        //獲取快取佇列中的一個請求
                            final Request e = (Request)this.mCacheQueue.take();
                            e.addMarker("cache-queue-take");
                            //如果請求取消了則將請求停止掉
                            if(e.isCanceled()) {
                                e.finish("cache-discard-canceled");
                            } else {
                            //檢視是否有快取的響應
                                Entry entry = this.mCache.get(e.getCacheKey());
                                //如果快取響應為空,則將請求加入網路請求佇列
                                if(entry == null) {
                                    e.addMarker("cache-miss");
                                    this.mNetworkQueue.put(e);
                                //判斷快取響應是否過期    
                                } else if(!entry.isExpired()) {
                                    e.addMarker("cache-hit");
                                    //對資料進行解析並回撥給主執行緒
                                    Response response = e.parseNetworkResponse(new NetworkResponse(entry.data, entry.responseHeaders));
                                    e.addMarker("cache-hit-parsed");
                                    if(!entry.refreshNeeded()) {
                                        this.mDelivery.postResponse(e, response);
                                    } else {
                                        e.addMarker("cache-hit-refresh-needed");
                                        e.setCacheEntry(entry);
                                        response.intermediate = true;
                                        this.mDelivery.postResponse(e, response, new Runnable() {
                                            public void run() {
                                                try {
                                                    CacheDispatcher.this.mNetworkQueue.put(e);
                                                } catch (InterruptedException var2) {
                                                    ;
                                                }

                                            }
                                        });
                                    }
                                } else {
                                    e.addMarker("cache-hit-expired");
                                    e.setCacheEntry(entry);
                                    this.mNetworkQueue.put(e);
                                }
                            }
                        } catch (InterruptedException var4) {
                            if(this.mQuit) {
                                return;
                            }
                        }
                    }
                }
            }
        }
    }

    static {
        DEBUG = VolleyLog.DEBUG;
    }

看到四個while迴圈有些暈吧,讓我們挑重點的說,首先從快取佇列取出請求,判斷是否請求是否被取消了,如果沒有則判斷該請求是否有快取的響應,如果有並且沒有過期則對快取響應進行解析並回撥給主執行緒。接下來看看網路排程執行緒。

4.NetworkDispatcher網路排程執行緒

NetworkDispatcher的run()方法:

 public void run() {
        Process.setThreadPriority(10);

        while(true) {
            long startTimeMs;
            Request request;
            while(true) {
                startTimeMs = SystemClock.elapsedRealtime();

                try {
                //從佇列中取出請求
                    request = (Request)this.mQueue.take();
                    break;
                } catch (InterruptedException var6) {
                    if(this.mQuit) {
                        return;
                    }
                }
            }

            try {
                request.addMarker("network-queue-take");
                if(request.isCanceled()) {
                    request.finish("network-discard-cancelled");
                } else {
                    this.addTrafficStatsTag(request);
                    //請求網路
                    NetworkResponse e = this.mNetwork.performRequest(request);
                    request.addMarker("network-http-complete");
                    if(e.notModified && request.hasHadResponseDelivered()) {
                        request.finish("not-modified");
                    } else {
                        Response volleyError1 = request.parseNetworkResponse(e);
                        request.addMarker("network-parse-complete");
                        if(request.shouldCache() && volleyError1.cacheEntry != null) {                         
                            //將響應結果存入快取
                            this.mCache.put(request.getCacheKey(), volleyError1.cacheEntry);
                            request.addMarker("network-cache-written");
                        }

                        request.markDelivered();
                        this.mDelivery.postResponse(request, volleyError1);
                    }
                }
            } catch (VolleyError var7) {
                var7.setNetworkTimeMs(SystemClock.elapsedRealtime() - startTimeMs);
                this.parseAndDeliverNetworkError(request, var7);
            } catch (Exception var8) {
                VolleyLog.e(var8, "Unhandled exception %s", new Object[]{var8.toString()});
                VolleyError volleyError = new VolleyError(var8);
                volleyError.setNetworkTimeMs(SystemClock.elapsedRealtime() - startTimeMs);
                this.mDelivery.postError(request, volleyError);
            }
        }
    }

網路排程執行緒也是從佇列中取出請求並且判斷是否被取消了,如果沒取消就去請求網路得到響應並回撥給主執行緒。請求網路時呼叫this.mNetwork.performRequest(request),這個mNetwork是一個介面,實現它的類是BasicNetwork,我們來看看BasicNetwork的performRequest()方法:

  public NetworkResponse performRequest(Request<?> request) throws VolleyError {
        long requestStart = SystemClock.elapsedRealtime();

        while(true) {
            HttpResponse httpResponse = null;
            Object responseContents = null;
            Map responseHeaders = Collections.emptyMap();

            try {
                HashMap e = new HashMap();
                this.addCacheHeaders(e, request.getCacheEntry());
                httpResponse = this.mHttpStack.performRequest(request, e);
                StatusLine statusCode1 = httpResponse.getStatusLine();
                int networkResponse1 = statusCode1.getStatusCode();
                responseHeaders = convertHeaders(httpResponse.getAllHeaders());
                if(networkResponse1 == 304) {
                    Entry requestLifetime2 = request.getCacheEntry();
                    if(requestLifetime2 == null) {
                        return new NetworkResponse(304, (byte[])null, responseHeaders, true, SystemClock.elapsedRealtime() - requestStart);
                    }

                    requestLifetime2.responseHeaders.putAll(responseHeaders);
                    return new NetworkResponse(304, requestLifetime2.data, requestLifetime2.responseHeaders, true, SystemClock.elapsedRealtime() - requestStart);
                }


...省略

從上面可以看到在12行呼叫的是HttpStack的performRequest()方法請求網路,接下來根據不同的響應狀態碼來返回不同的NetworkResponse。另外HttpStack也是一個介面,實現它的兩個類我們在前面已經提到了就是HurlStack和HttpClientStack。讓我們再回到NetworkDispatcher,請求網路後,會將響應結果存在快取中,如果響應結果成功則呼叫this.mDelivery.postResponse(request, volleyError1)來回撥給主執行緒。來看看Delivery的postResponse()方法:

 public void postResponse(Request<?> request, Response<?> response, Runnable runnable) {
        request.markDelivered();
        request.addMarker("post-response");
        this.mResponsePoster.execute(new ExecutorDelivery.ResponseDeliveryRunnable(request, response, runnable));
    }

來看看ResponseDeliveryRunnable裡面做了什麼:

 private class ResponseDeliveryRunnable implements Runnable {
        private final Request mRequest;
        private final Response mResponse;
        private final Runnable mRunnable;

        public ResponseDeliveryRunnable(Request request, Response response, Runnable runnable) {
            this.mRequest = request;
            this.mResponse = response;
            this.mRunnable = runnable;
        }

        public void run() {
            if(this.mRequest.isCanceled()) {
                this.mRequest.finish("canceled-at-delivery");
            } else {
                if(this.mResponse.isSuccess()) {
                    this.mRequest.deliverResponse(this.mResponse.result);
                } else {
                    this.mRequest.deliverError(this.mResponse.error);
                }

                if(this.mResponse.intermediate) {
                    this.mRequest.addMarker("intermediate-response");
                } else {
                    this.mRequest.finish("done");
                }

                if(this.mRunnable != null) {
                    this.mRunnable.run();
                }

            }
        }
    }

第17行呼叫了this.mRequest.deliverResponse(this.mResponse.result),這個就是實現Request<String>抽象類必須要實現的方法,我們來看看StringRequest的原始碼:

public class StringRequest extends Request<String> {
    private final Listener<String> mListener;

    public StringRequest(int method, String url, Listener<String> listener, ErrorListener errorListener) {
        super(method, url, errorListener);
        this.mListener = listener;
    }

    public StringRequest(String url, Listener<String> listener, ErrorListener errorListener) {
        this(0, url, listener, errorListener);
    }

    protected void deliverResponse(String response) {
        this.mListener.onResponse(response);
    }

 ...省略
}

在deliverResponse方法中呼叫了this.mListener.onResponse(response),最終將response回撥給了Response.Listener的onResponse()方法。我們用StringRequest請求網路的寫法是這樣的:

RequestQueue mQueue = Volley.newRequestQueue(getApplicationContext());
        StringRequest mStringRequest = new StringRequest(Request.Method.GET, "http://www.baidu.com",
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Log.i("wangshu", response);
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("wangshu", error.getMessage(), error);
            }
        });
        //將請求新增在請求佇列中
        mQueue.add(mStringRequest);

看到第5行整個Volley的大致流程都通了吧,好了關於Volley的原始碼就講到這裡。

相關文章