Volley源码解析(一)

Volley基本用法

本文章目的不在于介绍Volley的用法,仅对基本的用法进行介绍,意在引出源码解析的入口
Volley的基本用法通常为3步

  1. 创建RequestQueue
  2. 创建Request
  3. 将Request加入RequestQueue

以Josn请求为例

RequestQueue mQueue = Volley.newRequestQueue(context);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url, null,
		new Response.Listener() {
			@Override
			public void onResponse(JSONObject response) {
				Log.d("TAG", response.toString());
			}
		}, new Response.ErrorListener() {
			@Override
			public void onErrorResponse(VolleyError error) {
				Log.e("TAG", error.getMessage(), error);
			}
		});
mQueue.add(JsonObjectRequest);

Volley源码解读

此处先贴一张Volley的架构图,从guolin大神处搬来
Volley源码解析(一)_第1张图片
首先从我们使用Volley的入口出开始

RequestQueue mQueue = Volley.newRequestQueue(context);
  /**
     * Creates a default instance of the worker pool and calls {@link RequestQueue#start()} on it.
     *
     * @param context A {@link Context} to use for creating the cache dir.
     * @param stack An {@link HttpStack} to use for the network, or null for default.
     * @return A started {@link RequestQueue} instance.
     */
    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) {
                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;
    }

代码十分简洁,首先声明一个缓存文件cacheDir,http请求头userAgent ,
分别初始化声明HttpStack,Network,RequestQueue ,然后启动RequestQueue ,下面分别介绍一下各个类。
HttpStack

/**
     * Performs an HTTP request with the given parameters.
     *
     * 

A GET request is sent if request.getPostBody() == null. A POST request is sent otherwise, * and the Content-Type header is set to request.getPostBodyContentType().

* * @param request the request to perform * @param additionalHeaders additional headers to be sent together with * {@link Request#getHeaders()} * @return the HTTP response */
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError;

HttpStack接口只有一个方法performRequest,根据注释,可知这个方法为实际请求http访问的方法。该接口有两个实现类,分别对应使用HttpClient实现的HttpClientStack和使用HttpUrlConnection实现的HurlStack
Network

/**
     * Performs the specified request.
     * @param request Request to process
     * @return A {@link NetworkResponse} with data and caching metadata; will never be null
     * @throws VolleyError on errors
     */
    public NetworkResponse performRequest(Request<?> request) throws VolleyError;

BasicNetwork是Network的实现类之一,大略看一下子类重写的performRequest,可以看到其调用了HttpStack的performRequest,并返回了NetworkResponse
RequestQueue
构造方法只是初始化了几个对象,主要看start()方法

    /**
     * Starts the dispatchers in this queue.
     */
    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();
        }
    }

CacheDispatcher和NetworkDispatcher均为Thread子类,即启动了一个缓存线程和默认的4个Network线程。
各个类主要方法就这些,然后我们继续跟着start()方法追踪。
首先看 mCacheDispatcher.start(); 实际执行的方法为其run()方法,省略一些其他方法,如下

 public void run() {
        ...
        // 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.
                ...
            } catch (InterruptedException e) {
                // We may have been interrupted because it was time to quit.
                if (mQuit) {
                    return;
                }
                continue;
            }
        }
    }
}

首先是Cache的相关初始化,然后此线程一直循环执行如下内容:
从mCacheQueue中取出一个Request对象,判断此Request对象是否被取消,是否已被缓存,如若未被缓存或者缓存已过期,就将之放入NetworkQueue等待重新请求,否则使用已缓存的内容,并根据是否需要刷新,决定是否将之加入NetworkQueue。缓存的使用待会在看。
继续看NetworkDispatcher的run()方法

  @Override
    public void run() {
        while (true) {
       		...
            request = mQueue.take();
            
            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;
                }
				...
                // 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);
            	...
        }
    }

此线程也是一直循环取NetworkQueue中的请求,如果request未被取消,则调用BasicNetwork请求访问,返回NetworkResponse ,并解析为用户需要的Response,如果需要缓存,则将此Response放入缓存队列中,最后调用mDelivery.postResponse,返回给用户。

例子的第二步为构建一个Request,就不在看了。

第三步是将这个Request加入mQueue中,看一下add方法

/**
     * Adds a Request to the dispatch queue.
     * @param request The request to service
     * @return The passed-in request
     */
    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;
        }
    }

首先将Request设置为属于此Queue,然后判断是否需要缓存,不需要的话就直接加入NetworkQueue等待被使用,否则的话,继续判断该Request是否已请求过,若为新请求,则将之加入缓存队列CacheQueue以及重复队列WaitingRequests,若为重复请求,就在重复请求队列中,该CacheKey对应的位置中加入该请求。

整个流程到此结束,下一篇分析请求过程,回调过程,缓存过程。

你可能感兴趣的:(Android)