網(wǎng)站首頁 編程語言 正文
項(xiàng)目結(jié)構(gòu)
把源碼 clone 下來 , 可以看到 retrofit 整體結(jié)構(gòu)如下
圖 http包目錄下就是一些http協(xié)議常用接口 , 比如 請求方法 url , 請求體, 請求行 之類的
retrofit 使用
把retrofit使用作為分析的切入口吧 , retrofit單元測試使用如下
public final class BasicCallTest {
@Rule public final MockWebServer server = new MockWebServer();
interface Service {
@GET("/") Call<ResponseBody> getBody();
}
@Test public void responseBody() throws IOException {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(server.url("/"))
.build();
Service example = retrofit.create(Service.class);
server.enqueue(new MockResponse().setBody("1234"));
Response<ResponseBody> response = example.getBody().execute();
assertEquals("1234", response.body().string());
}
}
Retrofit 構(gòu)建 , 以構(gòu)建者模式構(gòu)建出Retrofit
可以看到builer可以配置baseUrl , 回調(diào)線程池 , 還有一些適配器的工廠 , 這些適配器的作用后面說
Retrofit #create
從create 方法開始分析 , 跟進(jìn)看下create 方法
public <T> T create(final Class<T> service) {
validateServiceInterface(service);
return (T)
Proxy.newProxyInstance(
service.getClassLoader(),
new Class<?>[] {service},
new InvocationHandler() {
private final Object[] emptyArgs = new Object[0];
@Override
public @Nullable 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);
}
args = args != null ? args : emptyArgs;
Platform platform = Platform.get();
return platform.isDefaultMethod(method)
? platform.invokeDefaultMethod(method, service, proxy, args)
: loadServiceMethod(method).invoke(args);
}
});
}
service 是請求的接口的class , 動態(tài)代理只能是接口 , 所以validateServiceInterface 先驗(yàn)證是不是接口 , 不是接口則拋異常。
method.getDeclaringClass() 獲取聲明類的Class。
比如 A類 有個method , method.getDeclaringClass() 返回為A.class , 如果method聲明類是Object.class 則直接method.invoke , 往下執(zhí)行毫無意義。
Platform#get()會根據(jù)當(dāng)前平臺獲取Platform 。
有點(diǎn)類似狀態(tài)模式思想 , 根據(jù)當(dāng)前的平臺選擇合適的子類
public boolean isDefaultMethod(Method method) {
return method.isDefault();
}
isDefault , 在接口類型中以default關(guān)鍵字聲明 則返回true, 比如
interface InterfaceWithDefault {
void firstMethod();
default void newMethod() {
System.out.println("newMethod");
}
}
所以此處會返回 false 接著調(diào)用 loadServiceMethod。
ServiceMethod #parseAnnotations
跟進(jìn)ServiceMethod #parseAnnotations
static <T> ServiceMethod<T> parseAnnotations(Retrofit retrofit, Method method) {
RequestFactory requestFactory = RequestFactory.parseAnnotations(retrofit, method);
return HttpServiceMethod.parseAnnotations(retrofit, method, requestFactory);
}
根據(jù)當(dāng)前的方法信息構(gòu)建出RequestFactory , 然后把具體實(shí)現(xiàn)細(xì)節(jié)交給HttpServiceMethod 處理 , HttpServiceMethod 繼承自ServiceMethod , 有三個子類 。
我們在Api.class定義的方法 , 解析并不是由HttpServiceMethod 完成 , 而是由RequestFactory去處理的 , 比如解析方法的注解。
更多的解析方法如下
方法解析的細(xì)節(jié)就不說了 , 繼續(xù)看RequestFactory 這個類 , 這個類的作用難道就是負(fù)責(zé)方法信息的解析 , 感覺和名字不太符合 , RequestFactory 顧名思義應(yīng)該是用來構(gòu)建Request的工廠 , 果不其然內(nèi)部還有個 create 方法 , 用來構(gòu)建okhttp3.Request的
//RequestFactory #create
okhttp3.Request create(Object[] args) throws IOException {
return requestBuilder.get().tag(Invocation.class, new Invocation(method, argumentList)).build();
}
就只有這一個create方法 , 難道retrofit 就只能使用okhttp來負(fù)責(zé)網(wǎng)絡(luò)請求 ? 答案是肯定的 , 從最開始的 loadServiceMethod(method).invoke(args)也可以看出 , 方法里面只構(gòu)建出OkHttpCall 沒提供api可以讓我們切換到其他的網(wǎng)絡(luò)請求庫。
但是 , Call 又抽象成接口的形式 ,如下, 這么做的目的可能是以后便于框架的維護(hù)
沿途風(fēng)景再美麗 , 也要回到主線路 , 繼續(xù)分析 HttpServiceMethod#parseAnnotations
HttpServiceMethod#parseAnnotations
這個方法太長 , 貼關(guān)鍵代碼吧
static <ResponseT, ReturnT> HttpServiceMethod<ResponseT, ReturnT> parseAnnotations(
Retrofit retrofit, Method method, RequestFactory requestFactory) {
boolean isKotlinSuspendFunction = requestFactory.isKotlinSuspendFunction;
boolean continuationWantsResponse = false;
boolean continuationBodyNullable = false;
boolean continuationIsUnit = false;
Annotation[] annotations = method.getAnnotations();
Type adapterType;
if (isKotlinSuspendFunction) {
Type[] parameterTypes = method.getGenericParameterTypes();
Type responseType =
Utils.getParameterLowerBound(
0, (ParameterizedType) parameterTypes[parameterTypes.length - 1]);
if (getRawType(responseType) == Response.class && responseType instanceof ParameterizedType) {
continuationWantsResponse = true;
}
} else {
//非kt 協(xié)程情況
adapterType = method.getGenericReturnType();
}
CallAdapter<ResponseT, ReturnT> callAdapter =
createCallAdapter(retrofit, method, adapterType, annotations);
Type responseType = callAdapter.responseType();
Converter<ResponseBody, ResponseT> responseConverter =
createResponseConverter(retrofit, method, responseType);
okhttp3.Call.Factory callFactory = retrofit.callFactory;
if (!isKotlinSuspendFunction) {
//非kt 協(xié)程情況
return new CallAdapted<>(requestFactory, callFactory, responseConverter, callAdapter);
} else if (continuationWantsResponse) {
return (HttpServiceMethod<ResponseT, ReturnT>)
new SuspendForResponse<>(
requestFactory,
callFactory,
responseConverter,
(CallAdapter<ResponseT, Call<ResponseT>>) callAdapter);
} else {
return (HttpServiceMethod<ResponseT, ReturnT>)
new SuspendForBody<>(
requestFactory,
callFactory,
responseConverter,
(CallAdapter<ResponseT, Call<ResponseT>>) callAdapter,
continuationBodyNullable,
continuationIsUnit);
}
}
構(gòu)建出HttpServiceMethod分兩種情況 :
- kotlin 協(xié)程情況
- 非Kotlin 協(xié)程情況
第二種 非Kotlin協(xié)程情況
第一種情況稍許復(fù)雜 , 先分析第二種
adapterType = method.getGenericReturnType();
@GET("/") Call<ResponseBody> getBody();
如果是上面代碼 , method.getGenericReturnType() = Call , 然后根據(jù)方法的返回值類型 / 方法注解信息 , 構(gòu)建出CallAdapter 。
createCallAdapter() 方法會使用 CallAdapter.Factory 構(gòu)建CallAdapter , 因?yàn)槌跏蓟痳etrofit的時候沒有配置CallAdapter.Factory , 所以會使用默認(rèn)的DefaultCallAdapterFactory。
最終會進(jìn)入DefaultCallAdapterFactory#get 。
DefaultCallAdapterFactory#get
這個方法作用就是返回CallAdapter , 修改下源碼加入兩個打印。
public @Nullable CallAdapter<?, ?> get(
Type returnType, Annotation[] annotations, Retrofit retrofit) {
final Type responseType = Utils.getParameterUpperBound(0, (ParameterizedType) returnType);
System.out.println("TAG" + " ->" + "returnType = " +getRawType(returnType) .getSimpleName());
System.out.println("TAG" + " ->" + "responseType = " +getRawType(responseType) .getSimpleName());
return new CallAdapter<Object, Call<?>>() {
@Override
public Type responseType() {
return responseType;
}
@Override
public Call<Object> adapt(Call<Object> call) {
return executor == null ? call : new ExecutorCallbackCall<>(executor, call);
}
};
}
運(yùn)行可以看到以下打印信息
returnType = Call ,responseType =ResponseBody 。
總結(jié)一下 , returnType就是方法返回值 , responseType 就是方法返回值上的泛型 DefaultCallAdapterFactory會根據(jù)平臺環(huán)境去構(gòu)建。
以Android24分析 , DefaultCallAdapterFactory(Executor callbackExecutor) , 構(gòu)造方法中 , 線程池為主線程池 , 在retrofit初始化的時候添加到 到callAdapterFactories 集合中。
至此 , CallAdapterFactory 和 CallAdapter 分析完了 , 總結(jié)下就是給Call (retrofit內(nèi)存只有OkHttpCall 作為唯一實(shí)現(xiàn)類)做適配 , 讓其可以在 Rxjava / 協(xié)程 等各個環(huán)境中使用 Call。
非kt 協(xié)程情況下 , parseAnnotations 方法最終返回的是將requestFactory , callFactory , responseConverter, callAdapter 封裝好的CallAdapted 對象。
再次回到夢開始的地方Retrofit#create 方法 , loadServiceMethod獲取的ServiceMethod最終實(shí)現(xiàn)類為CallAdapted , 獲取之后會調(diào)用invoke方法 , invoke是一個final方法 , 里面構(gòu)建了OkHttpCall , 然后調(diào)用了adapt方法 , adapt中調(diào)用了callAdapter.adapt(call)。
@Override
protected ReturnT adapt(Call<ResponseT> call, Object[] args) {
return callAdapter.adapt(call);
}
這里的ReturnT 就是ExecutorCallbackCall<>(executor, call) 對象 , 所以 example.getBody().execute() 就是調(diào)用ExecutorCallbackCall#execute方法
//ExecutorCallbackCall#execute
public Response<T> execute() throws IOException {
return delegate.execute();
}
delegate為OkHttpCall , 所以就調(diào)用到OkHttpCallCall#execute方法 , 這里就轉(zhuǎn)給Okhttp去請求網(wǎng)絡(luò)加載數(shù)據(jù)了 , 代碼就不貼了 , 我們看下網(wǎng)絡(luò)請求之后 , 數(shù)據(jù)Response 的處理 , 關(guān)鍵代碼OkHttpCall#parseResponse。
Response<T> parseResponse(okhttp3.Response rawResponse) throws IOException {
ResponseBody rawBody = rawResponse.body();
ExceptionCatchingResponseBody catchingBody = new ExceptionCatchingResponseBody(rawBody);
try {
T body = responseConverter.convert(catchingBody);
return Response.success(body, rawResponse);
}
}
responseConverter 在 HttpServiceMethod#parseAnnotations 方法中獲取 , 回應(yīng)數(shù)據(jù)轉(zhuǎn)換器 , 把數(shù)據(jù)轉(zhuǎn)換成我們可以直接使用的對象 , 比如我們常用的 GsonConverterFactory。
最后把轉(zhuǎn)換好之后的數(shù)據(jù) , 封裝成Response對象返回。
response.body()就是responseConverter 轉(zhuǎn)換后的數(shù)據(jù) 來張大致流程圖感受下吧
第一種 Kotlin協(xié)程情況
其實(shí)大致流程第二種情況分析的差不多了 , 接下來分析下Retrofit對于kotlin的特殊處理吧。
if (Utils.getRawType(parameterType) == Continuation.class) {
isKotlinSuspendFunction = true;
return null;
}
協(xié)程掛起方法 , 第一個參數(shù)為Continuation , 所以判斷是不是掛起方法也很簡單 , 根據(jù)ResponseType 去構(gòu)建協(xié)程專用的HttpServiceMethod , 主要有兩類。
- SuspendForResponse , 對應(yīng)type為Continuation<Response>
- SuspendForBody , 對應(yīng)type為Continuation
這里看下 SuspendForBody 實(shí)現(xiàn) , 套娃情況就不分析了。
如果是這樣使用 , 最終會調(diào)到SuspendForBody #adapt。
@Override
protected Object adapt(Call<ResponseT> call, Object[] args) {
call = callAdapter.adapt(call);
Continuation<ResponseT> continuation = (Continuation<ResponseT>) args[args.length - 1];
try {
//去掉干擾代碼 , 僅保留這個
return KotlinExtensions.awaitNullable(call, continuation);
}
}
這個地方就很關(guān)鍵了 , java 直接調(diào)kotlin 協(xié)程 suspend 方法。
KotlinExtensions.awaitNullable 會調(diào)到KotlinExtensions#await方法。
retrofit與協(xié)程適配的細(xì)節(jié)都在 KotlinExtensions這個類里。
進(jìn)入await , 可以看到使用suspendCancellableCoroutine把回調(diào)裝換成協(xié)程。
@JvmName("awaitNullable")
suspend fun <T : Any> Call<T?>.await(): T? {
return suspendCancellableCoroutine { continuation ->
continuation.invokeOnCancellation {
cancel()
}
enqueue(object : Callback<T?> {
override fun onResponse(call: Call<T?>, response: Response<T?>) {
if (response.isSuccessful) {
continuation.resume(response.body())
} else {
continuation.resumeWithException(HttpException(response))
}
}
override fun onFailure(call: Call<T?>, t: Throwable) {
continuation.resumeWithException(t)
}
})
}
}
其實(shí)內(nèi)部也是調(diào)用 OkHttp Call.enqueue() , 只不過是用suspendCancellableCoroutine給協(xié)程做了一層包裝處理
通過 suspendCancellableCoroutine包裝之后使用就很簡單了。
GlobalScope.launch {
try {
val result = xxxApi.getXxx()
} catch (exception: Exception) {
}
}
總結(jié)
Call 這個接口用于與網(wǎng)絡(luò)請求庫做適配 , 比如Okhttp。
CallAdapter 用于retrofit 與各種環(huán)境搭配使用做適配 , 比如rxjava / 協(xié)程 / java。
Converter 用于將請求結(jié)果轉(zhuǎn)換實(shí)體類Bean 或者其他。
用到的設(shè)計模式有: 動態(tài)代理/靜態(tài)代理 / 構(gòu)建者 / 工廠 / 適配器 / 狀態(tài) 等。
原文鏈接:https://juejin.cn/post/7124611158329262087
相關(guān)推薦
- 2023-01-18 React手寫redux過程分步講解_React
- 2023-02-05 Redis處理高并發(fā)之布隆過濾器詳解_Redis
- 2022-12-27 flutter?text組件使用示例詳解_Android
- 2021-12-15 C語言數(shù)據(jù)結(jié)構(gòu)與算法之圖的遍歷(二)_C 語言
- 2022-10-03 如何在python中實(shí)現(xiàn)capl語言里的回調(diào)函數(shù)(推薦)_python
- 2022-05-01 Entity?Framework系統(tǒng)架構(gòu)與原理介紹_基礎(chǔ)應(yīng)用
- 2022-01-14 2022年了--你還不會手寫promise? 完成promise的所有實(shí)現(xiàn)
- 2022-07-06 C#多線程之線程池ThreadPool詳解_C#教程
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運(yùn)行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運(yùn)算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實(shí)現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡單動態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊(duì)列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支