【OpenFeign】【源码+图解】【四】FeignClient实例工具类ReflectiveFeign
【OpenFeign】【源码+图解】【三】FeignClient的配置信息
5. FeignClient实例工具类ReflectiveFeign
上文中调用了targeter.target(this, builder, context, target)
,其实DefaultTargeter的作用只是中转,没有做任何事情,如下图
因此我们就直接分析Feign$Builder.target()方法
public static class Builder extends BaseBuilder<Builder> {
public <T> T target(Target<T> target) {
// 1、先build()出Feign
// 2、Feign.newInstance(target)
return build().newInstance(target);
}
// 创建ReflectiveFeign,ReflectiveFeign用于创建OpenFeign接口的实例
public Feign build() {
// 1.1、增强Builder属性
super.enrich();
// 1.2、创建SynchronousMethodHandler.Factory
SynchronousMethodHandler.Factory synchronousMethodHandlerFactory =
new SynchronousMethodHandler.Factory(client, retryer, requestInterceptors,
responseInterceptor, logger, logLevel, dismiss404, closeAfterDecode,
propagationPolicy, forceDecoding);
// 1.3、创建ParseHandlersByName
ParseHandlersByName handlersByName
new ParseHandlersByName(contract, options, encoder, decoder, queryMapEncoder,
errorDecoder, synchronousMethodHandlerFactory);
// 1.4、创建ReflectiveFeign
return new ReflectiveFeign(handlersByName, invocationHandlerFactory, queryMapEncoder);
}
}
在这一节中主要分析build()步骤,这里分两步
5.1 增强Builder属性
5.1.1 Capability
在开始之前我们得先认识下Capability
从类图中可以看到,最终要的是enrich(Object componentToEnrich, Class<?> capabilityToEnrich, List<Capability> capabilities)
方法,它的作用的给componentToEnrich对象添加上capabilities的capabilityToEnrich功能,那么capabilityToEnrich都有哪些功能呢?看下Capability
以上就是能够添加的功能。为了能更好理解,我们举个例子
1、前面提到可以自己配置Capability,创建一个实现类MyCapability,给它添加一个实现方法,用来enrich当前Builder的Options属性
// 1、实现Capability接口
public class MyCapability implements Capability {
// 2、覆盖enrich(Options options)方法
@Override
public Options enrich(Options options) {
// 3、返回新建的Options, 设置connectTimeout为11, readTimeout为22
return new Options(11, TimeUnit.SECONDS, 22, TimeUnit.SECONDS, false);
}
}
2、在yml文件中配置
feign:
client:
config:
product:
capabilities:
- com.lanna.openfeign.custom.MyCapability
3、 在Builder类的第209行和211行打断点,重新启动,进入第一个断点时查看Builder的属性,如下图
经过super.enrich()
后进入第二个断点
再查看Builder的属性,可见已经被更改了,说明MyCapability已经起作用。
上面介绍完Capability的作用,现在就该看看它的源码是怎么实现的了
public interface Capability {
static Object enrich(Object componentToEnrich,
Class<?> capabilityToEnrich,
List<Capability> capabilities) {
return capabilities.stream()
.reduce( // reduce的功能类似foreach,在这里就是遍历capabilities逐个enrich
componentToEnrich, // 初始值
(target, capability) -> invoke(target, capability, capabilityToEnrich), // 累加器
(component, enrichedComponent) -> enrichedComponent); // 最终值
}
static Object invoke(Object target, Capability capability, Class<?> capabilityToEnrich) {
return Arrays.stream(capability.getClass().getMethods())
.filter(method -> method.getName().equals("enrich")) // enrich方法
.filter(method -> method.getReturnType().isAssignableFrom(capabilityToEnrich)) // 返回值是Builder中的参数类型
.findFirst()
.map(method -> {
try {
// method: MyCapability.enrich(feign.Request$Options)
// capability: MyCapability
// target: feign.Request$Options
return method.invoke(capability, target);
} catch (IllegalAccessException | IllegalArgumentException
| InvocationTargetException e) {
throw new RuntimeException("Unable to enrich " + target, e);
}
})
.orElse(target); // 没有enrich方法的话返回原值
}
}
了解了Capability,对于Builder中的enrich
就很好理解了
public abstract class BaseBuilder<B extends BaseBuilder<B>> {
protected B enrich() {
if (capabilities.isEmpty()) {
// 如果没有capabilities直接返回
return thisB;
}
// getFieldsToEnrich()获取需要增强的属性
getFieldsToEnrich().forEach(field -> {
field.setAccessible(true);
try {
// 1. 获取属性的值
final Object originalValue = field.get(thisB);
final Object enriched;
// 2. 增强属性
if (originalValue instanceof List) {
// 如果是列表的话先一个一个enrich再归纳,如requestInterceptors
Type ownerType = ((ParameterizedType) field.getGenericType()).getActualTypeArguments()[0];
enriched = ((List) originalValue).stream()
.map(value -> Capability.enrich(value, (Class<?>) ownerType, capabilities))
.collect(Collectors.toList());
} else {
// 给原始值originalValue添加capabilities功能
enriched = Capability.enrich(originalValue, field.getType(), capabilities);
}
field.set(thisB, enriched);
} catch (IllegalArgumentException | IllegalAccessException e) {
throw new RuntimeException("Unable to enrich field " + field, e);
} finally {
field.setAccessible(false);
}
});
return thisB;
}
}
5.2 创建ReflectiveFeign
public static class Builder extends BaseBuilder<Builder> {
public Feign build() {
// 1.1、
super.enrich();
// 1.2、创建SynchronousMethodHandler.Factory,将当前builder的参数赋给SynchronousMethodHandler.Factory
SynchronousMethodHandler.Factory synchronousMethodHandlerFactory =
new SynchronousMethodHandler.Factory(client, retryer, requestInterceptors,
responseInterceptor, logger, logLevel, dismiss404, closeAfterDecode,
propagationPolicy, forceDecoding);
// 1.3、创建ParseHandlersByName,将当前builder的参数赋给ParseHandlersByName
ParseHandlersByName handlersByName
new ParseHandlersByName(contract, options, encoder, decoder, queryMapEncoder,
errorDecoder, synchronousMethodHandlerFactory);
// 1.4、创建ReflectiveFeign
return new ReflectiveFeign(handlersByName, invocationHandlerFactory, queryMapEncoder);
}
}
ReflectiveFeign创建好后就开始下一章节的newInstance()
public static class Builder extends BaseBuilder<Builder> {
public <T> T target(Target<T> target) {
// 1、先build()出Feign
// 2、Feign.newInstance(target)
return build().newInstance(target);
}
}