版權聲明:本文為LooperJing原創(chuàng)文章,轉(zhuǎn)載請注明出處!
在上一篇,流行網(wǎng)絡庫第(一)篇---Volley用法解析中了解了Volley的基本使用,但是對于Volley可能有些朋友還不是特別清楚。我也是結合源碼與其他人的分析,才真正弄清楚Volley的工作原理。
先看一個Demo,Volley十幾行代碼就完成了一次HTPP請求,我們看看這段代碼內(nèi)部究竟發(fā)生了什么?
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RequestQueue mQueue = Volley.newRequestQueue(MainActivity.this);
mQueue.add(getStringRequest());
}
public StringRequest getStringRequest() {
return new StringRequest("https://suggest.taobao.com/sug?code=utf-8&q=beizi",
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.e(getClass().getName(), response);
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e(getClass().getName(), error.getMessage());
}
}
);
}
}
首先第一句代碼,創(chuàng)建一個消息隊列
RequestQueue mQueue = Volley.newRequestQueue(MainActivity.this);
創(chuàng)建消息隊列的邏輯,被封裝在Volley中,以靜態(tài)方法暴露出來,供外部調(diào)用,總共有3個重載方法,上面使用的是第一個方法(只有一個參數(shù)),第一個方法會調(diào)用第二個方法(兩個參數(shù)),第二個方法會調(diào)用第三個方法(三個參數(shù))。
public static RequestQueue newRequestQueue(Context context) {
return newRequestQueue(context, null);
}
public static RequestQueue newRequestQueue(Context context, HttpStack stack){
return newRequestQueue(context, stack, -1);
}
public static RequestQueue newRequestQueue(Context context, int maxDiskCacheBytes) {
return newRequestQueue(context, null, maxDiskCacheBytes);
}
現(xiàn)在看第三個構造方法中做了什么?,這是第一個重點。
public static RequestQueue newRequestQueue(Context context, HttpStack stack, int maxDiskCacheBytes) {
//應用的默認緩存目錄,DEFAULT_CACHE_DIR值是volley,即文件cacheDir的文件名是volley
File cacheDir = new File(context.getCacheDir(), DEFAULT_CACHE_DIR);
// 通過應用程序的包名和版本信息來完善userAgent字符串
String userAgent = "volley/0";
try {
String packageName = context.getPackageName();
PackageInfo info = context.getPackageManager().getPackageInfo(packageName, 0);
userAgent = packageName + "/" + info.versionCode;
} catch (NameNotFoundException e) {
}
//如果stack為NULL,就建立一個默認的HttpStack
if (stack == null) {
if (Build.VERSION.SDK_INT >= 9) {
//版本在2.3之后,創(chuàng)建HurlStack,其內(nèi)部用了HttpURLConnection
stack = new HurlStack();
} else {
//版本在2.3之前,創(chuàng)建HttpClientStack,其內(nèi)部用了HttpClient
stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent));
}
}
//將stack傳到Network中,Network是負責網(wǎng)絡請求的
Network network = new BasicNetwork(stack);
RequestQueue queue;
//創(chuàng)建RequestQueue時要傳入一個Cache對象,用來做磁盤緩存
if (maxDiskCacheBytes <= -1) {
// No maximum size specified
queue = new RequestQueue(new DiskBasedCache(cacheDir), network);
} else{
// Disk cache size specified
queue = new RequestQueue(new DiskBasedCache(cacheDir, maxDiskCacheBytes), network);
}
// 開始請求隊列
queue.start();
return queue;
}
注釋都寫清楚了,主要就是在創(chuàng)建請求隊列的時候,做一些初始化的工作。
- 1、創(chuàng)建應用緩存目錄,這個目錄是volley;
- 2、 通過應用程序的包名和版本信息來完善userAgent字符串,這個userAgent只有在使用HttpClientStack才有用到;
- 3、如果用戶沒有建立stack,就建立一個默認的Stack,這里根據(jù)版本號判斷使用 HttpURLConnection還是使用HttpClient創(chuàng)建Stack;
- 4、創(chuàng)建Stack的目的是作為參數(shù)創(chuàng)建Network,Network是負責網(wǎng)絡請求的;
- 5、有了Network和DiskBasedCache,最后創(chuàng)建消息隊列并且開啟消息隊列。
到這里你可能還不知道,做這些初始化操作的目的是什么,繼續(xù)看。
看到最后返回的是RequestQueue對象,我們現(xiàn)在看RequestQueue是怎么工作的。先看看RequestQueue里面幾個重要的成員變量。
public class RequestQueue {
//等待隊列,當之前已經(jīng)存在了與本次請求相同的請求時,會把相同的請求放在隊列中,以URL為關鍵字(key)
private final Map<String, Queue<Request<?>>> mWaitingRequests =
new HashMap<String, Queue<Request<?>>>();
//存放所有請求,包括已經(jīng)運行的和正在等待的請求(Request)
private final Set<Request<?>> mCurrentRequests = new HashSet<Request<?>>();
//表示目前緩存的請求隊列,這個隊列會被傳入到CacheDispatcher做判斷。
private final PriorityBlockingQueue<Request<?>> mCacheQueue =
new PriorityBlockingQueue<Request<?>>();
//表示請求網(wǎng)絡連接的隊列,里面的請求都會向服務器進行請求(這才是唯一和服務器打交道的隊列)。
private final PriorityBlockingQueue<Request<?>> mNetworkQueue =
new PriorityBlockingQueue<Request<?>>();
// Volley類中調(diào)用的構造函數(shù),傳入了默認的網(wǎng)絡線程數(shù),DEFAULT_NETWORK_THREAD_POOL_SIZE = 4(默認是4個線程)
private static final int DEFAULT_NETWORK_THREAD_POOL_SIZE = 4;
//緩存相關
private final Cache mCache;
//網(wǎng)絡請求相關
private final Network mNetwork;
//請求結果分發(fā)器,會把響應得到的結果發(fā)送到主線程的回調(diào)方法中,最終傳遞給監(jiān)聽器。
private final ResponseDelivery mDelivery;
//阻塞式線程數(shù)組,不斷循環(huán)處理Request。
private NetworkDispatcher[] mDispatchers;
//阻塞式線程,不斷循環(huán)處理Request。
private CacheDispatcher mCacheDispatcher;
//請求完成時的監(jiān)聽數(shù)組
private List<RequestFinishedListener> mFinishedListeners =
new ArrayList<RequestFinishedListener>();
public static interface RequestFinishedListener<T> {
public void onRequestFinished(Request<T> request);
}
}
上面的成員變量代表的意思,請看注釋,現(xiàn)在看如何創(chuàng)建一個RequestQueue。這是第二個重點。
public RequestQueue(Cache cache, Network network, int threadPoolSize,
ResponseDelivery delivery) {
//初始化了network,dispatchers,delivery,cache對象,這里的cache是磁盤緩存的對象
//初始化完成后,立刻調(diào)用了start()方法
mCache = cache;
mNetwork = network;
mDispatchers = new NetworkDispatcher[threadPoolSize];
mDelivery = delivery;
}
public RequestQueue(Cache cache, Network network, int threadPoolSize) {
this(cache, network, threadPoolSize,
new ExecutorDelivery(new Handler(Looper.getMainLooper())));
}
public RequestQueue(Cache cache, Network network) {
this(cache, network, DEFAULT_NETWORK_THREAD_POOL_SIZE);
}
public void start() {
//先停止兩個阻塞式線程
stop();
//創(chuàng)建一個緩存線程(緩存分發(fā)器),不斷的處理Request
mCacheDispatcher = new CacheDispatcher(mCacheQueue, mNetworkQueue, mCache, mDelivery);
mCacheDispatcher.start();
//創(chuàng)建4個網(wǎng)絡線程(網(wǎng)絡分發(fā)器),不斷的處理Request
for (int i = 0; i < mDispatchers.length; i++) {
NetworkDispatcher networkDispatcher = new NetworkDispatcher(mNetworkQueue, mNetwork,
mCache, mDelivery);
mDispatchers[i] = networkDispatcher;
networkDispatcher.start();
}
}
//停止5個阻塞式線程,一個緩存線程,4個網(wǎng)絡線程
public void stop() {
if (mCacheDispatcher != null) {
mCacheDispatcher.quit();
}
for (int i = 0; i < mDispatchers.length; i++) {
if (mDispatchers[i] != null) {
mDispatchers[i].quit();
}
}
}
現(xiàn)在看看,其實
RequestQueue mQueue = Volley.newRequestQueue(MainActivity.this);
這一行代碼,原來做了這么多的事情,用最后兩行代碼來概括
RequestQueue queue = new RequestQueue(new DiskBasedCache(cacheDir),network);
queue.start();
就是創(chuàng)建了一個RequestQueue對象,調(diào)用start對象,開啟了4個線程,同時我們要記清楚,RequestQueue并不是一個簡單的Queue,內(nèi)部有好幾個Queue,其中mCurrentRequests 存放所有請求,包括已經(jīng)運行的和正在等待的請求;mCacheQueue (Request)表示目前緩存的請求隊列,這個隊列會被傳入到CacheDispatcher做判斷;mNetworkQueue 表示請求網(wǎng)絡連接的隊列,里面的請求都會向服務器進行請求(這才是唯一和服務器打交道的隊列)。并且RequestQueue中還創(chuàng)建了5個線程,其中CacheDispatcher是緩存線程,數(shù)量為1,NetworkDispatcher是網(wǎng)絡線程,存放在mDispatchers中,數(shù)量默認為4。
RequestQueue準備好了,現(xiàn)在該看看,往里面add了。這是第三個重點。
mQueue.add(getStringRequest());
add方法如下
public <T> Request<T> add(Request<T> request) {
//每個request的內(nèi)部維持著一個RequestQueue,先給內(nèi)部維持的RequestQueue賦值
request.setRequestQueue(this);
synchronized (mCurrentRequests) {
//mCurrentRequests中保存了所有的request,所以一上來就添加
mCurrentRequests.add(request);
}
//設置request的序列號
request.setSequence(getSequenceNumber());
// 設置request當前的真正進行的事件,標記現(xiàn)在是被添加到隊列中了
request.addMarker("add-to-queue");
// 如果不允許有磁盤緩存,跳過mCacheQueue,直接把request添加到networkQueue中,然后去請求網(wǎng)絡
if (!request.shouldCache()) {
// 添加到mNetworkQueue中,進行網(wǎng)絡交互
mNetworkQueue.add(request);
return request;
}
// Insert request into stage if there's already a request with the same cache key in flight.
//mWaitingRequests保存了當前正在執(zhí)行的請求與等待的請求
synchronized (mWaitingRequests) {
//這個cacheKey是請求的url和請求方式Method拼接起來的,保證了Key的唯一性
String cacheKey = request.getCacheKey();
// 判斷等待隊列中是否已經(jīng)有這個request,如果有了就需要過濾重復請求
if (mWaitingRequests.containsKey(cacheKey)) {
// There is already a request in flight. Queue up.
// mWaitingRequests的類型是HashMap<String, Queue<Request<?>>>
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;
}
}
請注意mWaitingRequests,mWaitingRequests的類型是HashMap<String, Queue<Request<?>>>,保存的對象是 Queue<Request<?>>,其中鍵是cacheKey,這個cacheKey是請求的url和請求方式Method拼接起來的,理論上如果重復了,就可以認為是同一個請求,Queue<Request<?>>中保存的是request,所以當我們連續(xù)添加了3個一樣的請求,那么mWaitingRequests中內(nèi)部維持的Queue<Request<?>>就有3個Request。
上面分析了Volley中開了5個線程,最先開啟的就是緩存線程了。
public void start() {
stop();
mCacheDispatcher = new CacheDispatcher(mCacheQueue, mNetworkQueue, mCache, mDelivery);
//先開啟緩存線程
mCacheDispatcher.start();
for (int i = 0; i < mDispatchers.length; i++) {
NetworkDispatcher networkDispatcher = new NetworkDispatcher(mNetworkQueue, mNetwork,
mCache, mDelivery);
mDispatchers[i] = networkDispatcher;
//在開啟網(wǎng)絡線程
networkDispatcher.start();
}
}
所以我們看一下,當一個request已經(jīng)添加到了mWaitingRequests中了,緩存線程mCacheDispatcher是怎么處理它的。注意CacheDispatcher接收了mCacheQueue, mNetworkQueue, mCache, mDelivery這些參數(shù)。
先看看CacheDispatcher類的成員。
public class CacheDispatcher extends Thread {
private static final boolean DEBUG = VolleyLog.DEBUG;
//緩存隊列
private final BlockingQueue<Request<?>> mCacheQueue;
//網(wǎng)路請求隊列
private final BlockingQueue<Request<?>> mNetworkQueue;
/** The cache to read from. */
private final Cache mCache;
//將響應分發(fā)到主線程
private final ResponseDelivery mDelivery;
/** Used for telling us to die. */
private volatile boolean mQuit = false;
public CacheDispatcher(
BlockingQueue<Request<?>> cacheQueue, BlockingQueue<Request<?>> networkQueue,
Cache cache, ResponseDelivery delivery) {
mCacheQueue = cacheQueue;
mNetworkQueue = networkQueue;
mCache = cache;
mDelivery = delivery;
}
}
主要看CacheDispatcher線程中的run方法,這是第四個重點。
@Override
public void run() {
if (DEBUG) VolleyLog.v("start new dispatcher");
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
// 初始化緩存區(qū),就把之前文件中所保存的對象,一個一個讀出來,保存在Map<String, CacheHeader> mEntries這個變量中
mCache.initialize();
Request<?> request;
while (true) {
// release previous request object to avoid leaking request object when mQueue is drained.
request = null;
try {
// 從cache隊列中取出一個request對象
request = mCacheQueue.take();
} catch (InterruptedException e) {
// We may have been interrupted because it was time to quit.
if (mQuit) {
return;
}
continue;
}
try {
// 設置當前事件名稱,標記緩存隊列中取出的
request.addMarker("cache-queue-take");
// 如果這個request已經(jīng)被取消了,就直接finish掉,進行下一次循環(huán)
if (request.isCanceled()) {
request.finish("cache-discard-canceled");
continue;
}
//上面緩存區(qū)已經(jīng)被初始化,所以可以從緩沖區(qū)中取出一個緩存,從mCache內(nèi)部維持的mEntries中取
Cache.Entry entry = mCache.get(request.getCacheKey());
if (entry == null) {
// 設置當前事件名稱
request.addMarker("cache-miss");
// Cache miss; send off to the network dispatcher.
//加入到mNetworkQueue中,進行網(wǎng)絡請求,進行下一次循環(huán),處理下一次request
mNetworkQueue.put(request);
continue;
}
// entry不為null,但是已經(jīng)完全過期了,讓它重新訪問網(wǎng)絡
// If it is completely expired, just send it to the network.
if (entry.isExpired()) {
//設置當前事件名稱,標記緩存命中且過期
request.addMarker("cache-hit-expired");
request.setCacheEntry(entry);
//加入到mNetworkQueue中,進行下一次循環(huán),處理下一次request
mNetworkQueue.put(request);
continue;
}
//設置當前事件名稱,標記緩存命中
request.addMarker("cache-hit");
Response<?> response = request.parseNetworkResponse(
new NetworkResponse(entry.data, entry.responseHeaders));
//設置當前事件名稱,標記這個request已經(jīng)被解析了
request.addMarker("cache-hit-parsed");
// 判斷是否需要刷新
if (!entry.refreshNeeded()) {
// 發(fā)送到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.
final Request<?> finalRequest = request;
mDelivery.postResponse(request, response, new Runnable() {
@Override
public void run() {
try {
mNetworkQueue.put(finalRequest);
} catch (InterruptedException e) {
// Not much we can do about this.
}
}
});
}
} catch (Exception e) {
VolleyLog.e(e, "Unhandled exception %s", e.toString());
}
}
}
經(jīng)過一系列的操作得到的request,最終會把一個request解析成一個Response,調(diào)用的是parseNetworkResponse方法。不同的request有不同的parseNetworkResponse方法,我們最上面的Demo用的是StringRequest。
@Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String parsed;
try {
parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
} catch (UnsupportedEncodingException e) {
parsed = new String(response.data);
}
return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));
}
得到了Response之后,將這個Response交給mDelivery,mDelivery稱為數(shù)據(jù)分發(fā)器,最開始由構造函數(shù)傳進來的。關于數(shù)據(jù)的分發(fā),這是第五個重點。
mDelivery.postResponse(request, response);
在RequestQueue構造中,mDelivery被初始化,是個ExecutorDelivery對象。
public RequestQueue(Cache cache, Network network, int threadPoolSize,
ResponseDelivery delivery) {
mCache = cache;
mNetwork = network;
mDispatchers = new NetworkDispatcher[threadPoolSize];
mDelivery = delivery;
}
public RequestQueue(Cache cache, Network network, int threadPoolSize) {
this(cache, network, threadPoolSize,
new ExecutorDelivery(new Handler(Looper.getMainLooper())));
}
ExecutorDelivery是個接口,繼承ResponseDelivery
public interface ResponseDelivery {
/**
* Parses a response from the network or cache and delivers it.
*/
public void postResponse(Request<?> request, Response<?> response);
/**
* Parses a response from the network or cache and delivers it. The provided
* Runnable will be executed after delivery.
*/
public void postResponse(Request<?> request, Response<?> response, Runnable runnable);
/**
* Posts an error for the given request.
*/
public void postError(Request<?> request, VolleyError error);
}
ExecutorDelivery內(nèi)部有一個Runnable,/用于分發(fā)網(wǎng)絡的響應結果到主線程的,這是第六個重點。
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) {
mRequest = request;
mResponse = response;
mRunnable = runnable;
}
@SuppressWarnings("unchecked")
@Override
public void run() {
// 看看是否已經(jīng)被取消了,如果被取消了,結束它,不做分發(fā)處理
if (mRequest.isCanceled()) {
//設置當前事件名稱,標記request被取消
mRequest.finish("canceled-at-delivery");
return;
}
// 分發(fā)一個的響應結果
if (mResponse.isSuccess()) {
//成功回調(diào)
mRequest.deliverResponse(mResponse.result);
} else {
//錯誤回調(diào)
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 {
//設置當前事件名稱,標記request已經(jīng)完成
mRequest.finish("done");
}
// If we have been provided a post-delivery runnable, run it.
if (mRunnable != null) {
mRunnable.run();
}
}
}
mListener,mErrorListener就是我們Demo中設置的回調(diào)接口。
@Override
protected void deliverResponse(String response) {
if (mListener != null) {
mListener.onResponse(response);
}
}
public void deliverError(VolleyError error) {
if (mErrorListener != null) {
mErrorListener.onErrorResponse(error);
}
}
現(xiàn)在再看那張圖
其中藍色部分代表主線程,綠色部分代表緩存線程,橙色部分代表網(wǎng)絡線程。我們在主線程中調(diào)用RequestQueue的add()方法來添加一條網(wǎng)絡請求,這條請求會先被加入到緩存隊列當中,如果發(fā)現(xiàn)可以找到相應的緩存結果就直接讀取緩存并解析,然后回調(diào)給主線程。如果在緩存中沒有找到結果,則將這條請求加入到網(wǎng)絡請求隊列中,然后處理發(fā)送HTTP請求,解析響應結果,寫入緩存,并回調(diào)主線程。
Volley工作流程總結:http://www.cnblogs.com/tianzhijiexian/p/4264468.html
- 當一個RequestQueue被成功申請后會開啟一個CacheDispatcher(緩存調(diào)度器)和4個(默認)NetworkDispatcher(網(wǎng)絡請求調(diào)度器);
- CacheDispatcher緩存調(diào)度器最為第一層緩沖,開始工作后阻塞的從緩存序列mCacheQueue中取得請求:
a. 對于已經(jīng)取消了的請求,直接標記為跳過并結束這個請求
b. 全新或過期的請求,直接丟入mNetworkQueue中交由N個NetworkDispatcher進行處理
c. 已獲得緩存信息(網(wǎng)絡應答)卻沒有過期的請求,交由Request的parseNetworkResponse進行解析,從而確定此應答是否成功。然后將請求和應答交由Delivery分發(fā)者進行處理,如果需要更新緩存那么該請求還會被放入mNetworkQueue中 - 用戶將請求Request add到RequestQueue之后:
a. 對于不需要緩存的請求(需要額外設置,默認是需要緩存)直接丟入mNetworkQueue交由N個NetworkDispatcher處理;
b. 對于需要緩存的,全新的請求加入到mCacheQueue中給CacheDispatcher處理
c. 需要緩存,但是緩存列表中已經(jīng)存在了相同URL的請求,放在mWaitingQueue中做暫時雪藏,待之前的請求完畢后,再重新添加到mCacheQueue中; - 網(wǎng)絡請求調(diào)度器NetworkDispatcher作為網(wǎng)絡請求真實發(fā)生的地方,對消息交給BasicNetwork進行處理,同樣的,請求和結果都交由Delivery分發(fā)者進行處理;
- Delivery分發(fā)者實際上已經(jīng)是對網(wǎng)絡請求處理的最后一層了,在Delivery對請求處理之前,Request已經(jīng)對網(wǎng)絡應答進行過解析,此時應答成功與否已經(jīng)設定。而后Delivery根據(jù)請求所獲得的應答情況做不同處理:
a. 若應答成功,則觸發(fā)deliverResponse方法,最終會觸發(fā)開發(fā)者為Request設定的Listener
b. 若應答失敗,則觸發(fā)deliverError方法,最終會觸發(fā)開發(fā)者為Request設定的ErrorListener
處理完后,一個Request的生命周期就結束了,Delivery會調(diào)用Request的finish操作,將其從mRequestQueue中移除,與此同時,如果等待列表中存在相同URL的請求,則會將剩余的層級請求全部丟入mCacheQueue交由CacheDispatcher進行處理。
一個Request的生命周期:
- 通過add加入mRequestQueue中,等待請求被執(zhí)行;
- 請求執(zhí)行后,調(diào)用自身的parseNetworkResponse對網(wǎng)絡應答進行處理,并判斷這個應答是否成功;
- 若成功,則最終會觸發(fā)自身被開發(fā)者設定的Listener;若失敗,最終會觸發(fā)自身被開發(fā)者設定的ErrorListener。
參考鏈接:
http://www.cnblogs.com/tianzhijiexian/p/4264468.html
http://blog.csdn.net/guolin_blog/article/details/17656437
http://blog.csdn.net/ttdevs/article/details/17764351
Please accept mybest wishes for your happiness and success !