项目中使用到了okhttp,但只是简单的会用,没有看过源码,作为程序员,没看过源码和咸鱼有什么区别。于是乎,土贼我打开Source Insight,看一看 okhttp是如何工作的。
OkHttpClient client = new OkHttpClient();这是一个简单的构建异步请求的demo,可以看到demo首先构建Request对象,然后调用OkHttpClient.newCall(request)创建call对象。
Request request = new Request.Builder()
.url("http://192.168.0.101/bim/project")
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.d("OkHttp", "Call Failed:" + e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
Log.d("OkHttp", "Call succeeded:" + response.message());
}
});
@Override public Call newCall(Request request) {这里创建的Call对象是一个RealCall对象 ,创建完RealCall对象之后,执行RealCall对象的enqueue()方法
return RealCall.newRealCall(this, request, false /* for web socket */);
}
@Override public void enqueue(Callback responseCallback) {首先检查这个RealCall对象是否被标记,标记过的表示这个请求已经被调用过了,然后调用Dispatcher的enqueue方法,这里传入的是AsyncCall对象,AsyncCall是RealCall的内部类。接下来我们看一下Dispatcher,Dispatcher是OkHttp的分发器,通过Dispatcher,将任务放入特定的队列,Dispatcher中有以下几个队列
synchronized (this) {
if (executed) throw new IllegalStateException("Already Executed");
executed = true;
}
captureCallStackTrace();
client.dispatcher().enqueue(new AsyncCall(responseCallback));
}
/** Ready async calls in the order they'll be run. */
private final Deque<AsyncCall> readyAsyncCalls = new ArrayDeque<>(); //等待异步队列
/** Running asynchronous calls. Includes canceled calls that haven't finished yet. */
private final Deque<AsyncCall> runningAsyncCalls = new ArrayDeque<>(); //运行异步队列
/** Running synchronous calls. Includes canceled calls that haven't finished yet. */
private final Deque<RealCall> runningSyncCalls = new ArrayDeque<>(); //运行同步队列
再看enqueue方法
synchronized void enqueue(AsyncCall call) {这里先判断运行异步队列大小是否小于maxRequests(64)以及对同一主机的访问Call数是否小于maxRequestsPerHost(5),如果小于就将AsyncCall放入运行异步队列中,并且调用线程池执行,否则加入等待异步队列。
if (runningAsyncCalls.size() < maxRequests && runningCallsForHost(call) < maxRequestsPerHost) {
runningAsyncCalls.add(call);
executorService().execute(call);
} else {
readyAsyncCalls.add(call);
}
}
最后我们看一下线程池的实现:
public synchronized ExecutorService executorService() {
if (executorService == null) {
executorService = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>(), Util.threadFactory("OkHttp Dispatcher", false));
}
return executorService;
}
这里通过ThreadPoolExecutor创建线程池,核心线程池为0,最大线程数Integer.MAx_VALUE,线程KeepAlive 60秒, 任务队列 synchronousQueue,synchronousQueue队列是是一个不存储元素的阻塞队列,每一个put操作必须等待一个take操作,否则不能继续添加元素。
细心的人也看出来了,这个线程池其实是CachedThreadPool,这类线程池比较适合执行大量的耗时较少的任务。当整个线程池都处于闲置状态时,线程池中的线程都会超时而被停止,这个时候CachedThreadPool之中实际上是没有任何线程的,它几乎不占用任何资源。
总结:
okHttp先将请求封装成Call,然后调用分发器的enqueue方法,分发器判断异步运行队列中线程数目是否小于64以及对同一主机的请求是否小于5,如果小于就加入异步运行队列,并调用CachedThreadPool线程池执行,如果不小于则加入异步等待队列。