嗨,我是哈利迪~《看完不忘系列》将以从树干到细枝
的思路分析一些技术框架,本文将对开源项目Retrofit
进行介绍。
本文约2800字,阅读大约8分钟。
Retrofit源码基于最新版本2.9.0
预备
Retrofit使得网络调用可以像RESTful设计风格一样简洁,如:
interface WanApi {
@GET("article/list/{page}/json")
Call<WanArticleBean> articleList(@Path("page") int page);
}
又如,后端的Spring Boot框架通过约定大于配置
思想省去了很多配置,其在网络接口RestController上也运用了这种风格,
@RestController
public class ActivityController {
@Autowired
private ActivityService activityService;
@GetMapping("/goods")
public ResultEntity queryGoods(@RequestParam("page") int page) {
return activityService.queryGoods(page);
}
}
Retrofit的底层网络实现基于okhttp,自身的类不是很多,最核心的点就是动态代理
了。代理模式
简单来说,就是为对象提供一个增强
或控制其访问
的代理。下面我们先来了解下静态代理
和动态代理
~
静态代理
编译期就完成代理
源码级:手动编写代理类、APT生成代理类
字节码级:编译期生成字节码、
举个栗子,
interface 赚钱 {
void makeMoney(int income);
}
class 小鲜肉 implements 赚钱 {
@Override
public void makeMoney(int income) {
System.out.println("开拍,赚个" + income);
}
}
class 经纪人 implements 赚钱 {
赚钱 xxr;
public 经纪人(赚钱 xxr) {
this.xxr = xxr;
}
@Override
public void makeMoney(int income) {
if (income < 1000_0000) {
System.out.println("才" + income + ",先回去等通知吧");
} else {
xxr.makeMoney(income);
}
}
}
public static void main(String[] args) {
赚钱 xxr = new 小鲜肉();
赚钱 jjr = new 经纪人(xxr);
jjr.makeMoney(100_0000);
jjr.makeMoney(1000_0000);
}
为什么代理类
和委托类
要实现相同接口?是为了尽可能保证代理类
的内部结构和委托类
一致,这样对代理类
的操作都可以转移到委托类
上,代理类
只关注增强
和控制
。
动态代理
运行期生成字节码,如Proxy.newProxyInstance、CGLIB
Proxy.newProxyInstance是java自带,只能对接口代理(因为生成的类已经继承了Proxy,java没法多继承)
>
CGLIB则更强大,还能对普通类代理,底层基于ASM(ASM使用类似SAX解析器逐行扫描来提高性能)
举个栗子,
class 合作标准 implements InvocationHandler {
赚钱 xxr;
public 合作标准(赚钱 xxr) {
this.xxr = xxr;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
int income = (int) args[0];
if (income < 1000_0000) {
System.out.println("才" + income + ",先回去等通知吧");
return null;
} else {
return method.invoke(xxr, args);
}
}
}
public static void main(String[] args) {
赚钱 xxr = new 小鲜肉();
合作标准 standard = new 合作标准(xxr);
赚钱 bd = (赚钱) Proxy.newProxyInstance(赚钱.class.getClassLoader(),
new Class[]{赚钱.class},
standard);
//调用makeMoney,内部转发给了合作标准的invoke
bd.makeMoney(100_0000);
bd.makeMoney(1000_0000);
}
通过栗子可以看出,动态代理
不需要提前创建具体的代理类(如经纪人
或经纪公司
)去实现赚钱
接口,而是先拟一份合作标准
(InvocationHandler),等到运行期才创建代理类$Proxy0
(字节码),然后反射创建其实例商务拓展
,这样显得更为灵活。
了解完动态代理
,就可以开始Retrofit之旅了~
树干
简单使用
引入依赖,
implementation 'com.squareup.okhttp3:okhttp:3.14.9'
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
implementation 'com.google.code.gson:gson:2.8.6'
定义接口WanApi
,
interface WanApi {
@GET("article/list/{page}/json")
Call<WanArticleBean> articleList(@Path("page") int page);
}
发起请求,
class RetrofitActivity extends AppCompatActivity {
final String SERVER = "https://www.xxx.com/";
@Override
protected void onCreate(Bundle savedInstanceState) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(SERVER)
.addConverterFactory(GsonConverterFactory.create())
.build();
WanApi wanApi = retrofit.create(WanApi.class);
//得到Retrofit的call,他封装了okhttp的call
Call<WanArticleBean> call = wanApi.articleList(0);
call.enqueue(new Callback<WanArticleBean>() {
@Override
public void onResponse(Call<WanArticleBean> call, Response<WanArticleBean> response) {
WanArticleBean bean = response.body();
mBinding.tvResult.setText("" + bean.getData().getDatas().size());
}
@Override
public void onFailure(Call<WanArticleBean> call, Throwable t) {}
});
}
}
实现原理
由于Retrofit底层基于okhttp,哈迪在《看完不忘系列》之okhttp已经对网络流程做了分析,所以本文忽略网络实现只关注Retrofit自身的一些处理,Retrofit对象的构建就是简单的builder模式,我们直接看create,
public <T> T create(final Class<T> service) {
validateServiceInterface(service);
return (T)
Proxy.newProxyInstance(
service.getClassLoader(),
new Class<?>[] {service},
new InvocationHandler() {
private final Platform platform = Platform.get();
@Override
public Object invoke(Object proxy, Method method, Object[] args){
if (method.getDeclaringClass() == Object.class) {
return method.invoke(this, args);
}
return platform.isDefaultMethod(method)
? platform.invokeDefaultMethod(method, service, proxy, args)
: loadServiceMethod(method).invoke(args);
}
});
}
Proxy.newProxyInstance动态代理,运行期会生成一个类(字节码)如$ProxyN
,实现传入的接口即WanApi
,重写接口方法然后转发给InvocationHandler的invoke,如下(伪代码),
class $ProxyN extends Proxy implements WanApi{
Call<WanArticleBean> articleList(@Path("page") int page){
invocationHandler.invoke(this,method,args);
}
}
我们先看validateServiceInterface验证逻辑,
private void validateServiceInterface(Class<?> service) {
if (validateEagerly) {
Platform platform = Platform.get();
for (Method method : service.getDeclaredMethods()) {
if (!platform.isDefaultMethod(method) && !Modifier.isStatic(method.getModifiers())) {
loadServiceMethod(method);
}
}
}
}
如果开了validateEagerly,会一次性把接口WanApi
的所有方法都检查一遍并加载进来,可以在debug模式下开启,提前发现错误写法,比如在@GET请求设置了@Body这种错误就会抛出异常:
java.lang.IllegalArgumentException: Non-body HTTP method cannot contain @Body.
loadServiceMethod
然后是loadServiceMethod(method).invoke(args)
,看名字可知是先找方法,然后执行,
final Map<Method, ServiceMethod<?>> serviceMethodCache = new ConcurrentHashMap<>();
ServiceMethod<?> loadServiceMethod(Method method) {
ServiceMethod<?> result = serviceMethodCache.get(method);
if (result != null) return result;
synchronized (serviceMethodCache) {
result = serviceMethodCache.get(method);
if (result == null) {
result = ServiceMethod.parseAnnotations(this, method);
serviceMethodCache.put(method, result);
}
}
return result;
}
跟进ServiceMethod.parseAnnotations,
static <T> ServiceMethod<T> parseAnnotations(Retrofit retrofit, Method method) {
RequestFactory requestFactory = RequestFactory.parseAnnotations(retrofit, method);
return HttpServiceMethod.parseAnnotations(retrofit, method, requestFactory);
}
先看1. RequestFactory.parseAnnotations,
static RequestFactory parseAnnotations(Retrofit retrofit, Method method) {
return new Builder(retrofit, method).build();
}
class Builder {
RequestFactory build() {
for (Annotation annotation : methodAnnotations) {
parseMethodAnnotation(annotation);
}
int parameterCount = parameterAnnotationsArray.length;
parameterHandlers = new ParameterHandler<?>[parameterCount];
for (int p = 0, lastParameter = parameterCount - 1; p < parameterCount; p++) {
parameterHandlers[p] =
parseParameter(p, parameterTypes[p], parameterAnnotationsArray[p], p == lastParameter);
}
return new RequestFactory(this);
}
}
得到RequestFactory后,看2. HttpServiceMethod.parseAnnotations,HttpServiceMethod负责适配和转换处理,将接口方法的调用调整为HTTP调用,
static <ResponseT, ReturnT> HttpServiceMethod<ResponseT, ReturnT> parseAnnotations(
Retrofit retrofit, Method method, RequestFactory requestFactory) {
Annotation[] annotations = method.getAnnotations();
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;
return new CallAdapted<>(requestFactory, callFactory, responseConverter, callAdapter);
}
可见最终返回了一个CallAdapted,看到CallAdapted,
class CallAdapted<ResponseT, ReturnT> extends HttpServiceMethod<ResponseT, ReturnT> {
private final CallAdapter<ResponseT, ReturnT> callAdapter;
CallAdapted(
RequestFactory requestFactory,
okhttp3.Call.Factory callFactory,
Converter<ResponseBody, ResponseT> responseConverter,
CallAdapter<ResponseT, ReturnT> callAdapter) {
super(requestFactory, callFactory, responseConverter);
this.callAdapter = callAdapter;
}
@Override
protected ReturnT adapt(Call<ResponseT> call, Object[] args) {
return callAdapter.adapt(call);
}
}
那这个CallAdapter实例到底是谁呢,我们先回到Retrofit.Builder,
public Retrofit build() {
Executor callbackExecutor = this.callbackExecutor;
if (callbackExecutor == null) {
callbackExecutor = platform.defaultCallbackExecutor();
}
List<CallAdapter.Factory> callAdapterFactories = new ArrayList<>(this.callAdapterFactories);
callAdapterFactories.addAll(platform.defaultCallAdapterFactories(callbackExecutor));
}
DefaultCallAdapterFactory这个工厂创建具体的CallAdapter实例,
public CallAdapter<?, ?> get(Type returnType, Annotation[] annotations, Retrofit retrofit) {
final Type responseType = Utils.getParameterUpperBound(0, (ParameterizedType) returnType);
final Executor executor =
Utils.isAnnotationPresent(annotations, SkipCallbackExecutor.class)
? null
: callbackExecutor;
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);
}
};
}
invoke
前边loadServiceMethod
得到了CallAdapted,然后执行invoke,实现在父类HttpServiceMethod里,
final ReturnT invoke(Object[] args) {
Call<ResponseT> call = new OkHttpCall<>(requestFactory, args, callFactory, responseConverter);
return adapt(call, args);
}
class CallAdapted<ResponseT, ReturnT> extends HttpServiceMethod<ResponseT, ReturnT> {
private final CallAdapter<ResponseT, ReturnT> callAdapter;
@Override
protected ReturnT adapt(Call<ResponseT> call, Object[] args) {
return callAdapter.adapt(call);
}
}
然后是请求入队,ExecutorCallbackCall.enqueue -> OkHttpCall.enqueue,
void enqueue(final Callback<T> callback) {
delegate.enqueue(
new Callback<T>() {
@Override
public void onResponse(Call<T> call, final Response<T> response) {
callbackExecutor.execute(
() -> {
callback.onResponse(ExecutorCallbackCall.this, response);
});
}
@Override
public void onFailure(Call<T> call, final Throwable t) {}
});
}
void enqueue(final Callback<T> callback) {
okhttp3.Call call;
call.enqueue(new okhttp3.Callback() {
void onResponse(okhttp3.Call call, okhttp3.Response rawResponse) {
callback.onResponse(OkHttpCall.this, response);
}
})
}
总算把流程跑通了,回到前边再看一遍流程图,就豁然开朗了~
细枝
CallAdapter
CallAdapter适配器用于适配返回类型,比如还可以支持Rxjava、协程的使用,
interface WanApi {
@GET("article/list/{page}/json")
Call<WanArticleBean> articleList(@Path("page") int page);
@GET("article/list/{page}/json")
Observable<WanArticleBean> articleListRx(@Path("page") int page);
}
Converter
Converter转换器用于转换参数类型,比如把Long时间戳格式化成string再传给后端,
interface WanApi {
@GET("article/list/{page}/json")
Call<WanArticleBean> articleList(@Path("page") int page, @Query("cur") Long cur);
}
class TimeConverter implements Converter<Long, String> {
private SimpleDateFormat mFormat = new SimpleDateFormat("yyyy-MM-dd-HHmmss");
@Override
public String convert(Long value) throws IOException {
if (value > 1_000_000_000_000L) {
return mFormat.format(new Date(value));
}
return String.valueOf(value);
}
}
class TimeConverterFactory extends Converter.Factory {
@Override
public Converter<?, String> stringConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
if (type == Long.class) {
//使用自定义TimeConverter
return new TimeConverter();
}
return super.stringConverter(type, annotations, retrofit);
}
public static Converter.Factory create() {
return new TimeConverterFactory();
}
}
动态替换url
在构建Retrofit时传入HttpUrl对象,之后这个实例就一直存在不会更改,所以可以反射修改他的字段比如host,来实现动态替换服务端地址,
String SERVER = "https://www.xxx.com/";
HttpUrl httpUrl = HttpUrl.get(SERVER);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(httpUrl)
.build();
尾声
咱们下期见~😆
系列文章:
参考资料
欢迎关注原创技术公众号:哈利迪ei
评论