(一)是否可以自定義 HttpClient?
Retrofit 的靜態內部類 Builder 的 client(OkHttpClient client) 方法接收 OkHttpClient 參數,但其 callFactory(okhttp3.Call.Factory factory) 方法接收 okhttp3.Call.Factory 參數,那么也就可以自定義 HttpClient,只要實現 okhttp3.Call.Factory 的 Call newCall(Request request) 就行了唄。
public Builder client(OkHttpClient client) {
return callFactory(checkNotNull(client, "client == null"));
}
public Builder callFactory(okhttp3.Call.Factory factory) {
this.callFactory = checkNotNull(factory, "factory == null");
return this;
}
(二)預加載
我們知道 Retrofit 通過注解來解釋我們定義的接口方法,其中用到動態代理、反射以及解析的流程勢必會耗費時間,具體可以在自己項目中輸出 log 看下 create() 方法的耗時。
通常 app 在啟動到首頁的過程會請求多個接口,配置相關、檢測升級、拉取首頁數據等等,這種情況下可能會執行一大堆 loadServiceMethod() 方法,會帶來性能、速度方面的影響。這個時候我們就可以設置 validateEagerly 為 true 進行預加載,提前把將要用到的 serviceMethod 加載到內存里。
public <T> T create(final Class<T> service) {
Utils.validateServiceInterface(service);
// 判斷是否需要預加載
if (validateEagerly) {
eagerlyValidateMethods(service);
}
// 返回一個動態代理的類對象
return (T) Proxy.newProxyInstance(service.getClassLoader(), new Class<?>[] { service },
new InvocationHandler() {
private final Platform platform = Platform.get();
// 代理對象調用接口方法時,便會調用該 invoke() 方法
@Override public Object invoke(Object proxy, Method method, @Nullable Object[] args)
throws Throwable {
// If the method is a method from Object then defer to normal invocation.
if (method.getDeclaringClass() == Object.class) {
return method.invoke(this, args);
}
if (platform.isDefaultMethod(method)) {
return platform.invokeDefaultMethod(method, service, proxy, args);
}
// 此處也是通過 loadServiceMethod 方法來返回 serviceMethod
ServiceMethod<Object, Object> serviceMethod =
(ServiceMethod<Object, Object>) loadServiceMethod(method);
// 封裝了 OkHttpCall 實例來請求網絡,通常對應 OkHttp
OkHttpCall<Object> okHttpCall = new OkHttpCall<>(serviceMethod, args);
// 處理接口方法的返回類型
return serviceMethod.callAdapter.adapt(okHttpCall);
}
});
}
private void eagerlyValidateMethods(Class<?> service) {
Platform platform = Platform.get();
// 遍歷接口中的所有方法
for (Method method : service.getDeclaredMethods()) {
if (!platform.isDefaultMethod(method)) {
loadServiceMethod(method);
}
}
}
ServiceMethod<?, ?> loadServiceMethod(Method method) {
// 先從緩存中讀取,如果有則返回
ServiceMethod<?, ?> result = serviceMethodCache.get(method);
if (result != null) return result;
// 緩存中沒有,則構建新的并放入緩存
synchronized (serviceMethodCache) {
result = serviceMethodCache.get(method);
if (result == null) {
result = new ServiceMethod.Builder<>(this, method).build();
serviceMethodCache.put(method, result);
}
}
return result;
}
關于動態代理可以參考:代理模式及Java實現動態代理