转载请标明出处:http://blog.youkuaiyun.com/newhope1106/article/details/53615398
虽然网上有很多文章是分析Volley框架的,不过博客的作用,一个是让别人看了能够有所得,另一个是让自己同样的有所得。
1.首先来介绍一下Volley框架
(1)下载
sdk不能直接使用volley,需要自己编译,不过maven中提供了jar包下载,
http://mvnrepository.com/artifact/com.mcxiaoke.volley/library。
(2)介绍
引用网上的关于Volley的介绍,
Volley的中文翻译为“齐射、并发”,是在2013年的Google大会上发布的一款Android平台网络通信库,具有网络请求的处理、小图片的异步加载和缓存等功能,能够帮助 Android APP 更方便地执行网络操作,而且更快速高效。
在Google IO的演讲上,其配图是一幅发射火弓箭的图,有点类似流星。这表示,Volley特别适合数据量不大但是通信频繁的场景。见下图:
Volley 有如下的优点:
- 自动调度网络请求;
- 高并发网络连接;
- 通过标准的 HTTP cache coherence(高速缓存一致性)缓存磁盘和内存透明的响应;
- 支持指定请求的优先级;
- 网络请求cancel机制。我们可以取消单个请求,或者指定取消请求队列中的一个区域;
- 框架容易被定制,例如,定制重试或者回退功能;
- 包含了调试与追踪工具;
Volley 不适合用来下载大的数据文件。因为 Volley 会保持在解析的过程中所有的响应。对于下载大量的数据操作,请考虑使用 DownloadManager。
在volley推出之前我们一般会选择比较成熟的第三方网络通信库,如:android-async-http、retrofit、okhttp等。他们各有优劣,可有所斟酌地选择选择更适合项目的类库。...
(3)使用
下面我们给一个图片请求的范例:
private RequestQueue mRequestQueue;
if(mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(this);
}
ImageRequest imageRequest = new ImageRequest("http://g.hiphotos.bdimg.com/imgad/pic/item/6a63f6246b600c3341da97df1d4c510fd9f9a102.jpg",
new Response.Listener<Bitmap>() {
@Override
public void onResponse(Bitmap response) {
mImageView.setImageBitmap(response);
}
}, 0, 0, Bitmap.Config.RGB_565, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "image request error : " + error);
}
});
mRequestQueue.add(imageRequest);
2.其次来看一下Volley框架的UML类图
这里只看几个核心的类即可
3.从代码角度再来看一下Volley的实现
首先Volley使用了newRequestQueue给使用者调用,每次调用这个接口的时候就会自动创建一个请求队列-RequestQueue,同时会调用RequestQueue的start方法,此时会开启2种线程的调度器,一个缓存调度器(CacheDispatcher)和几个网络调度器(NetworkDispatcher,默认4个)。
(1)下面是通过调用newRequestQueue接口的代码,代码里面会根据SDK版本选择
HttpClient
和
HttpUrlConnection来处理网络操作。
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) {
}
/*如果没有指定处理网络请求的类,则根据sdk版本,选择HttpClient或者HttpUrlConnection */
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;
}
2)我们知道RequestQueue并不是什么线程,可以看看start接口里面的内容,其中CacheDispatcher和NetworkDispatcher 都是线程,CacheDispatcher负责处理是否将缓存队列的请求放到网络队列中,而NetworkDispatcher线程才是真正处理网络请求的地方。
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();
}
}
(3)上述初始化了2种类型的线程,再来看一下CacheDispatcher的run方法
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;
}
}
}
可以看到mNetworkQueue.put(request),这里就是把请求放到网络队列中。
(4)再来看看NetworkDispatcher的run方法。
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();
} 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) {
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);
}
}
}
(5)NetworkResponse networkResponse = mNetwork.performRequest(request);这一行是进行处理网络请求的地方,具体如何处理,可以看一下BasicNetwork这个类,默认用这个类来处理网络请求的。
public NetworkResponse performRequest(Request<?> request) throws VolleyError {
long requestStart = SystemClock.elapsedRealtime();
while (true) {
HttpResponse httpResponse = null;
byte[] responseContents = null;
Map<String, String> responseHeaders = Collections.emptyMap();
try {
// Gather headers.
Map<String, String> headers = new HashMap<String, String>();
addCacheHeaders(headers, request.getCacheEntry());
httpResponse = mHttpStack.performRequest(request, headers);
StatusLine statusLine = httpResponse.getStatusLine();
int statusCode = statusLine.getStatusCode();
responseHeaders = convertHeaders(httpResponse.getAllHeaders());
// Handle cache validation.
if (statusCode == HttpStatus.SC_NOT_MODIFIED) {
Entry entry = request.getCacheEntry();
if (entry == null) {
return new NetworkResponse(HttpStatus.SC_NOT_MODIFIED, null,
responseHeaders, true,
SystemClock.elapsedRealtime() - requestStart);
}
// A HTTP 304 response does not have all header fields. We
// have to use the header fields from the cache entry plus
// the new ones from the response.
// http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.5
entry.responseHeaders.putAll(responseHeaders);
return new NetworkResponse(HttpStatus.SC_NOT_MODIFIED, entry.data,
entry.responseHeaders, true,
SystemClock.elapsedRealtime() - requestStart);
}
// Some responses such as 204s do not have content. We must check.
if (httpResponse.getEntity() != null) {
responseContents = entityToBytes(httpResponse.getEntity());
} else {
// Add 0 byte response as a way of honestly representing a
// no-content request.
responseContents = new byte[0];
}
// if the request is slow, log it.
long requestLifetime = SystemClock.elapsedRealtime() - requestStart;
logSlowRequests(requestLifetime, request, responseContents, statusLine);
if (statusCode < 200 || statusCode > 299) {
throw new IOException();
}
return new NetworkResponse(statusCode, responseContents, responseHeaders, false,
SystemClock.elapsedRealtime() - requestStart);
} catch (SocketTimeoutException e) {
attemptRetryOnException("socket", request, new TimeoutError());
} catch (ConnectTimeoutException e) {
attemptRetryOnException("connection", request, new TimeoutError());
} catch (MalformedURLException e) {
throw new RuntimeException("Bad URL " + request.getUrl(), e);
} catch (IOException e) {
int statusCode = 0;
NetworkResponse networkResponse = null;
if (httpResponse != null) {
statusCode = httpResponse.getStatusLine().getStatusCode();
} else {
throw new NoConnectionError(e);
}
VolleyLog.e("Unexpected response code %d for %s", statusCode, request.getUrl());
if (responseContents != null) {
networkResponse = new NetworkResponse(statusCode, responseContents,
responseHeaders, false, SystemClock.elapsedRealtime() - requestStart);
if (statusCode == HttpStatus.SC_UNAUTHORIZED ||
statusCode == HttpStatus.SC_FORBIDDEN) {
attemptRetryOnException("auth",
request, new AuthFailureError(networkResponse));
} else {
// TODO: Only throw ServerError for 5xx status codes.
throw new ServerError(networkResponse);
}
} else {
throw new NetworkError(networkResponse);
}
}
}
}
上述代码包括
HttpUrlConnection(或HttpClient)请求网络,头部的处理等等,将结果封装进NetworkResponse中,再由ExecutorDelivery来处理请求,根据是否出错,来调用不同的回调方法。
(6)最后是网队列里面加入请求,框架里面提供了好多种请求,比如StringRequest、ImageRequest等
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;
}
}
4.离开代码来总结一下Volley的思想
软件架构设计原则中有一个原则是最少知识原则,这一原则也应该适合框架和开发者之间,让开发者在使用框架的时候,最少知道实现细节,一个优秀的框架基本上都实现了一点,隐藏实现细节,能让使用者基本上不需要花费多少代价就可以使用,而Volley当然也做到这一点,上面介绍Volley框架的时候就可以看到使用是多么的简单和方便了。
Volley框架把请求分为2种类型的,一种是优先级比较高的,会立马加入网络队列(NetworkQueue)中,另一种比较低的,加入缓存队列(CacheQueue)中等待。其中处理缓存队列的线程只有一个,处理网络队列的可以有多个。处理网络队列的线程会不断的从队列中取数据,如果不为空的话,就立即执行,然后调用返回结果处理回调。处理缓存队列的线程也是不断的从缓存队列中取请求,判断请求是否已经请求过,或者是否失效,或者是否需要重新刷新,如果没有请求过或者已经失效或者需要重新刷新的话,都会把它再加入到网络队列中等待处理。而其中有一个处理非常巧妙的地方在于重复的请求的处理,为了避免阻塞了短时间内加入缓存队列的不同请求,一起开始缓存队列相同的请求只保存一个,其他的相同都放入到一个根据url作为关键字的等待请求HashMap中,这样在处理缓存队列的线程里面,就可以顺利处理不同的请求了,而当一个请求处理完之后,它会把所有的相同请求一次性加入到缓存处理队列中,这样处理缓存的线程一次性可以连续的把所有的相同请求取出来,然后决定是否需要加入到网络队列中。而处理网络队列的线程则又加了相同的请求是否请求过、是否取消,是否需求刷新请求的规则,避免了大量重复的请求操作。
5.其他
里面缓存类,DiskBasedCache和其他一些细节可以查看源码了解,还是非常有趣的东西的。