SPI的入口类:ExtensionLoader
1.1. ExtensionLoader getExtensionLoader(Class type)
/**
* 根据扩展接口获取ExtensionLoader,一个扩充接口只会对应一个ExtensionLoader
* 整体逻辑:
* (1)校验扩展接口是否有@SPI注解
* (2)从缓存中获取与拓展接口对应的ExtensionLoader
* (3)若缓存未命中,则创建一个新的实例,并置入缓存
* 缓存:ConcurrentMap<Class<?>, ExtensionLoader<?>> EXTENSION_LOADERS
* @param type
* @param <T>
* @return
*/
@SuppressWarnings("unchecked")
public static <T> ExtensionLoader<T> getExtensionLoader(Class<T> type) {
if (type == null)
throw new IllegalArgumentException("Extension type == null");
//校验type是否为接口,dubbo中所有的扩展接口必须加@SPI注解
if(!type.isInterface()) {
throw new IllegalArgumentException("Extension type(" + type + ") is not interface!");
}
//校验type是否有@SPI注解
if(!withExtensionAnnotation(type)) {
throw new IllegalArgumentException("Extension type(" + type +
") is not extension, because WITHOUT @" + SPI.class.getSimpleName() + " Annotation!");
}
ExtensionLoader<T> loader = (ExtensionLoader<T>) EXTENSION_LOADERS.get(type);
if (loader == null) {
EXTENSION_LOADERS.putIfAbsent(type, new ExtensionLoader<T>(type));
loader = (ExtensionLoader<T>) EXTENSION_LOADERS.get(type);
}
return loader;
}
private ExtensionLoader(Class<?> type) {
this.type = type;
//类型是ExtensionFactory则(ExtensionFactory objectFactory)为null,否则为ExtensionFactory的适配类型实现
objectFactory = (type == ExtensionFactory.class ? null : ExtensionLoader.getExtensionLoader(ExtensionFactory.class).getAdaptiveExtension());
}
getExtensionLoader获取ExtensionLoader实例整体执行流程:
- (1)校验扩展接口是否有@SPI注解
- (2)从缓存中获取与拓展接口对应的ExtensionLoader
- (3)若缓存未命中,则创建一个新的实例,并置入缓存
ExtensionLoader.getExtensionLoader(ExtensionFactory.class).getAdaptiveExtension():将在后续流程中说明
2.1. 通过SPI机制获取想要的扩展接口对应的扩展实现类实例
有了ExtensionLoader实例,就可以通过SPI机制获取想要的扩展接口对应的扩展实现类实例了,以
“com.alibaba.dubbo.rpc.Protocol protocol = ExtensionLoader.getExtensionLoader(com.alibaba.dubbo.rpc.Protocol protocal.class).getExtension(“dubbo”); ”为例
/**
* 返回指定名字的扩展实现类实例。如果指定名字的扩展不存在,则抛异常 {@link IllegalStateException}.
* 整体逻辑:
* 1. name为true,则getDefaultExtension获取默认实现类,即:SPI注解的value属性会作为name
* eg: @SPI(value="xxx"),xxx代表扩展接口的默认扩展实现类是谁,name=xxx
* eg:Protocol的默认实现类为DubboProtocol,因为@SPI(value="dubbo")
* 2. 从缓存cachedInstances中获取扩展实现类实例
* 3. 缓存为命中,则创建实例,并置入缓存
* @param name
* @return
*/
@SuppressWarnings("unchecked")
public T getExtension(String name) {
if (name == null || name.length() == 0)
throw new IllegalArgumentException("Extension name == null");
//如果名称是true,则getDefaultExtension获取默认实现类,即:SPI注解的value属性会作为name
//eg: @SPI(value="xxx"),xxx代表扩展接口的默认扩展实现类是谁,name=xxx
if ("true".equals(name)) {
return getDefaultExtension();
}
//从缓存cachedInstances中获取扩展实现类实例的holder
Holder<Object> holder = cachedInstances.get(name);
if (holder == null) {
cachedInstances.putIfAbsent(name, new Holder<Object>());
holder = cachedInstances.get(name);
}
Object instance = holder.get();
if (instance == null) {
synchronized (holder) {
instance = holder.get();
if (instance == null) {
//不存在实例,根据name创建并置入到holder中
instance = createExtension(name);
holder.set(instance);
}
}
}
return (T) instance;
}
getExtension获取扩展实现类实例整体执行流程:
* (1) name为true,则getDefaultExtension获取默认实现类,即:SPI注解的value属性会作为name
* eg: @SPI(value=“xxx”),xxx代表扩展接口的默认扩展实现类是谁,name=xxx
* eg:Protocol的默认实现类为DubboProtocol,因为@SPI(value=“dubbo”)
* (2)从缓存cachedInstances中获取扩展实现类实例
* (3)缓存为命中,则创建实例,并置入缓存
2.1.1. 在“2.1. getExtension”中有2个相关方法getDefaultExtension()和createExtension(name),getDefaultExtension()流程分析在createExtension(name)中会包含,所以这里只分析createExtension(name)
/**
* 整体逻辑:
* (1)通过扩展名name找到扩展实现类Class,可能会触发SPI文件加载解析getExtensionClasses()
* (2)根据Class通过反射创建扩展实现类实例,并完成依赖注入
* (3)如果扩展接口有扩展包装类,实例化包装类,并将当前扩展实现类实例instance,通过构造函数注入到每个包装类
* (4)返回实例
* 如果有包装类,那么是所有包装类中最后一个包装类的实例
* 如果没有包装咧,那么是instance是扩展实现类的实例
* @param name
* @return
*/
@SuppressWarnings("unchecked")
private T createExtension(String name) {
//根据name获取扩张实现类的Class,为空则抛异常,getExtensionClasses会触发SPI文件加载
Class<?> clazz = getExtensionClasses().get(name);
if (clazz == null) {
throw findException(name);
}
try {
//缓存中获取扩展实现类实例,获取不到则通过反射创建实例并置入缓存
T instance = (T) EXTENSION_INSTANCES.get(clazz);
if (instance == null) {
EXTENSION_INSTANCES.putIfAbsent(clazz, (T) clazz.newInstance());
instance = (T) EXTENSION_INSTANCES.get(clazz);
}
//2. 接口扩展实现类通过setter依赖注入,依赖组件先从SPI机制构造查找,再从spring容器查找
injectExtension(instance);
//如果接口的扩展实现类有包装类(有接口类型的构造函数)
//遍历所有的包装类,将当前扩展实现类实例instance,通过构造函数注入到每个包装类
//最后返回的instance是遍历到的最后一个包装类的实例,这也是dubbo的aop实现机制
Set<Class<?>> wrapperClasses = cachedWrapperClasses;
if (wrapperClasses != null && wrapperClasses.size() > 0) {
for (Class<?> wrapperClass : wrapperClasses) {
//遍历wrapper类,包装实例并为wrapper类 injectExtension 注入扩展实现
instance = injectExtension((T) wrapperClass.getConstructor(type).newInstance(instance));
}
}
//如果没有包装类,那么是instance是扩展实现类的实例,否则是包装类的实例
return instance;
} catch (Throwable t) {
throw new IllegalStateException("Extension instance(name: " + name + ", class: " +
type + ") could not be instantiated: " + t.getMessage(), t);
}
}
createExtension整体逻辑:
- (1)通过扩展名name找到扩展实现类Class,可能会触发SPI文件加载解析getExtensionClasses()
- (2)根据Class通过反射创建扩展实现类实例,并完成依赖注入
- (3)如果扩展接口有扩展包装类,实例化包装类,并将当前扩展实现类实例instance,通过构造函数注入到每个包装类
- (4)返回实例
-
如果有包装类,那么是所有包装类中最后一个包装类的实例
-
如果没有包装咧,那么是instance是扩展实现类的实例
2.1.1.1. 在“2.1.1. createExtension”中有2个相关方法getExtensionClasses()和injectExtension(instance),这里先分析getExtensionClasses()
/**
* SPI文件加载解析,获取扩展接口对应的所有的扩展实现类Class,并置入缓存Map
* key:扩展配置文件中配置的key,val:扩展配置文件中配置的val,即扩展实现类全类名
* (1) 先从缓存获取Map<String, Class<?>>
* (2) 缓存获取不到加载解析SPI配置文件,然后置入缓存
* @return
*/
private Map<String, Class<?>> getExtensionClasses() {
//classes:key 扩展配置文件中配置的key,val 扩展配置文件中配置的val
Map<String, Class<?>> classes = cachedClasses.get();
if (classes == null) {
synchronized (cachedClasses) {
classes = cachedClasses.get();
//不存在则加载并缓存
if (classes == null) {
//加载类路径中的SPI配置文件,构造cachedClasses
classes = loadExtensionClasses();
cachedClasses.set(classes);
}
}
}
return classes;
}
/**
* 加载类路径中的SPI配置文件,构造cachedClasses,以及赋值相应属性
* 1. cachedDefaultName:设置默认的扩展实现类名称
* 2. 从3个目录加载:META-INF/dubbo/internal/、META-INF/dubbo/、META-INF/services/
* @return
*/
private Map<String, Class<?>> loadExtensionClasses() {
final SPI defaultAnnotation = type.getAnnotation(SPI.class);
if(defaultAnnotation != null) {//获取SPI注解,SPI(value="xxx"),xxx代表扩展接口的默认扩展实现类是谁
String value = defaultAnnotation.value();
if(value != null && (value = value.trim()).length() > 0) {
String[] names = NAME_SEPARATOR.split(value);//逗号分隔value
if(names.length > 1) {//只能有一个默认扩展实现类
throw new IllegalStateException("more than 1 default extension name on extension " + type.getName()
+ ": " + Arrays.toString(names));
}
if(names.length == 1) cachedDefaultName = names[0];
}
}
//loadFile方法加载扩展类:3个目录,META-INF/dubbo/internal/、META-INF/dubbo/、META-INF/services/
//key: 配置文件中的key, val:扩展实现类Class
Map<String, Class<?>> extensionClasses = new HashMap<String, Class<?>>();
loadFile(extensionClasses, DUBBO_INTERNAL_DIRECTORY);
loadFile(extensionClasses, DUBBO_DIRECTORY);
loadFile(extensionClasses, SERVICES_DIRECTORY);
return extensionClasses;
}
/**
* loadFile方法加载扩展类:3个目录,META-INF/dubbo/internal/、META-INF/dubbo/、META-INF/services/
* Map<String, Class<?>> extensionClasses
* key: 配置文件中的key, val:扩展实现类Class
* 1. 如果扩展实现类有@Adaptive,则将Class赋值给成员变量cachedAdaptiveClass
* 2. 如果扩展实现类是扩展接口type的包装类,所有包装类Class都会存入Set,Set<Class<?>> cachedWrapperClasses
* 3. 扩展实现类没有@Adaptive和也不是wapper类,则置入extensionClasses,
* @param extensionClasses
* @param dir
*/
private void loadFile(Map<String, Class<?>> extensionClasses, String dir) {
//拼接扩展接口全类名,作为文件名,eg:META-INF/dubbo/internal/com.alibaba.dubbo.rpc.Protocol
String fileName = dir + type.getName();
try {
Enumeration<java.net.URL> urls;
ClassLoader classLoader = findClassLoader();
//通过类加载器,获取类路径下指定文件名的文件URL
if (classLoader != null) {
urls = classLoader.getResources(fileName);
} else {
urls = ClassLoader.getSystemResources(fileName);
}
if (urls != null) {
while (urls.hasMoreElements()) { //遍历文件URL
java.net.URL url = urls.nextElement();
try {
//IO流读取文件
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "utf-8"));
try {
String line = null;
while ((line = reader.readLine()) != null) { //读取文件的每一行
final int ci = line.indexOf('#');//#为注释,故#后的内容忽略
if (ci >= 0) line = line.substring(0, ci);
line = line.trim();
if (line.length() > 0) {
try {
String name = null;
int i = line.indexOf('=');
if (i > 0) {
//myprotocol=com.kl.dubbotest.spi.MyProtocol
name = line.substring(0, i).trim();//扩展名
line = line.substring(i + 1).trim();//扩展全类名
}
if (line.length() > 0) {
//通过反射,获取实现类Class
Class<?> clazz = Class.forName(line, true, classLoader);
if (! type.isAssignableFrom(clazz)) { //扩展实现类是否实现了扩展接口type
throw new IllegalStateException("Error when load extension class(interface: " +
type + ", class line: " + clazz.getName() + "), class "
+ clazz.getName() + "is not subtype of interface.");
}
//扩展实现类是否有@Adaptive注解,置入缓存cachedAdaptiveClass
if (clazz.isAnnotationPresent(Adaptive.class)) {
if(cachedAdaptiveClass == null) {
cachedAdaptiveClass = clazz;
} else if (! cachedAdaptiveClass.equals(clazz)) {
//一个扩展接口的SPI实现,只能有一个扩展实现类是@Adaptive标记的
throw new IllegalStateException("More than 1 adaptive class found: "
+ cachedAdaptiveClass.getClass().getName()
+ ", " + clazz.getClass().getName());
}
} else {
//扩展实现类不存在@Adaptive
try {
//扩展实现类是否有参数为扩展接口类型的(比如 com.alibaba.dubbo.rpc.Protocol类型,并且1个参数)的构造函数
//表示它是个接口包装类Wrapper
//getConstructor若不存在这样的构造函数会报错
clazz.getConstructor(type);
Set<Class<?>> wrappers = cachedWrapperClasses;
if (wrappers == null) {
cachedWrapperClasses = new ConcurrentHashSet<Class<?>>();
wrappers = cachedWrapperClasses;
}
//将扩展实现类包装类Class缓存至cachedWrapperClasses
wrappers.add(clazz);
} catch (NoSuchMethodException e) { //不存在参数为Class type的构造函数,即不是包装Wrapper类型
clazz.getConstructor();//校验是否存在无参构造函数
//不在在name,只有val,即SPI配置文件中只有val没有key
if (name == null || name.length() == 0) {
//name为(eg: AdaptiveExtensionFactory去除ExtensionFactory,name为:adaptive)
name = findAnnotationName(clazz);
if (name == null || name.length() == 0) {
if (clazz.getSimpleName().length() > type.getSimpleName().length()
&& clazz.getSimpleName().endsWith(type.getSimpleName())) {
name = clazz.getSimpleName().substring(0, clazz.getSimpleName().length() - type.getSimpleName().length()).toLowerCase();
} else {
throw new IllegalStateException("No such extension name for the class " + clazz.getName() + " in the config " + url);
}
}
}
//逗号分隔name属性
String[] names = NAME_SEPARATOR.split(name);
if (names != null && names.length > 0) {
//扩展实现类,是否有Activate注解
Activate activate = clazz.getAnnotation(Activate.class);
if (activate != null) {
//如果有,将@Activate注解以names[0]为key缓存至cachedActivates
cachedActivates.put(names[0], activate);
}
//遍历names,将name以clazz为key缓存至cachedNames
for (String n : names) {
if (! cachedNames.containsKey(clazz)) {
//map key:扩展实现类Class, val:配置文件中的key
cachedNames.put(clazz, n);
}
Class<?> c = extensionClasses.get(n);
if (c == null) {
//将扩展实现类Class以name为key放入extensionClasses
//map key: 配置文件中的key, val:扩展实现类Class
//@Adaptive扩展实现类和wapper类都不在extensionClasses里,联系上下文
extensionClasses.put(n, clazz);
} else if (c != clazz) {
throw new IllegalStateException("Duplicate extension " + type.getName() + " name " + n + " on " + c.getName() + " and " + clazz.getName());
}
}
}
}
}
}
} catch (Throwable t) {
IllegalStateException e = new IllegalStateException("Failed to load extension class(interface: " + type + ", class line: " + line + ") in " + url + ", cause: " + t.getMessage(), t);
exceptions.put(line, e);
}
}
} // end of while read lines
} finally {
reader.close();
}
} catch (Throwable t) {
logger.error("Exception when load extension class(interface: " +
type + ", class file: " + url + ") in " + url, t);
}
} // end of while urls
}
} catch (Throwable t) {
logger.error("Exception when load extension class(interface: " +
type + ", description file: " + fileName + ").", t);
}
}
getExtensionClasses()整体流程:SPI文件加载解析,获取扩展接口对应的所有的扩展实现类Class,并置入缓存Map
- (1) 先从缓存获取Map<String, Class<?>> extensionClasses
key:扩展配置文件中配置的key,val:扩展配置文件中配置的val,即扩展实现类全类名 - (2) 缓存获取不到加载解析SPI配置文件
- (3) 获取默认的扩展实现类名称,赋值给成员变量cachedDefaultName
- (4) 从3个目录加载:META-INF/dubbo/internal/、META-INF/dubbo/、META-INF/services/
-
- 如果扩展实现类有@Adaptive,则将Class赋值给成员变量cachedAdaptiveClass
-
- 如果扩展实现类是扩展接口type的包装类,所有包装类Class都会存入Set,Set<Class<?>> cachedWrapperClasses
-
- 扩展实现类没有@Adaptive和也不是wapper类,则置入Map<String, Class<?>> extensionClasses
- (5) 最后置入缓存
2.1.1.2. 在“2.1.1. createExtension”中有2个相关方法getExtensionClasses()和injectExtension(instance),这里分析injectExtension(instance)
/**
* 通过setter给扩展实现类实例依赖注入属性
* 根据setter方法对应的参数类型和property名称从ExtensionFactory中查询,如果有获取到实例,那么就进行注入操作
*
* setter方法字段类型可以是SPI接口类型,或者是Spring bean类型
* 依赖注入的字段,是通过ExtensionLoader的objectFactory获取到的
* objectFacotry 会根据先后通过spi机制和从spring 容器里获取属性对象并注入。
* @param instance
* @return
*/
private T injectExtension(T instance) {
try {
if (objectFactory != null) {
//遍历扩展实现类实例的所有的方法
for (Method method : instance.getClass().getMethods()) {
//获取所有的public,并且只有一个参数,set方法
if (method.getName().startsWith("set")
&& method.getParameterTypes().length == 1
&& Modifier.isPublic(method.getModifiers())) {
//获取参数类型
Class<?> pt = method.getParameterTypes()[0];
try {
//objectFactory.getExtension工厂获取注入类型实例,根据set方法参数类型及set方法截取set之后剩余部分取小写
//根据set方法名构造要赋值的属性名,setProtocol方法property=protocol
String property = method.getName().length() > 3 ? method.getName().substring(3, 4).toLowerCase() + method.getName().substring(4) : "";
//根据类型,名称信息从ExtensionFactory获取
//通过getExtension的方法获取属性对象,所以还要看getExtension的实现
Object object = objectFactory.getExtension(pt, property);
if (object != null) {
///如果不为空,set方法的参数是扩展点类型,那么进行注入
//通过反射,赋值对象属性
method.invoke(instance, object);
}
} catch (Exception e) {
logger.error("fail to inject via method " + method.getName()
+ " of interface " + type.getName() + ": " + e.getMessage(), e);
}
}
}
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
return instance;
}
这也是dubbo-ioc的原理:
- 通过setter给扩展实现类实例依赖注入属性,
- setter方法字段类型可以是SPI接口类型,或者是Spring bean类型
- 依赖注入的字段,是通过ExtensionLoader的objectFactory获取到的
- objectFacotry 会根据先后通过spi机制和从spring 容器里获取属性对象并注入
ExtensionFactory接口3个实现类
@Adaptive
public class AdaptiveExtensionFactory implements ExtensionFactory {
private final List<ExtensionFactory> factories;
/**
* 把其他ExtensionFactory扩展实现类实例,加入factories list
* AdaptiveExtensionFactory、SpiExtensionFactory、SpringExtensionFactory
*/
public AdaptiveExtensionFactory() {
ExtensionLoader<ExtensionFactory> loader = ExtensionLoader.getExtensionLoader(ExtensionFactory.class);
List<ExtensionFactory> list = new ArrayList<ExtensionFactory>();
//getSupportedExtensions()返回的是非包装类扩展,非Adaptive扩展
for (String name : loader.getSupportedExtensions()) {
list.add(loader.getExtension(name));
}
factories = Collections.unmodifiableList(list);
}
/**
* 遍历factories,通过factory.getExtension(type, name)获取bean
* @param type object type.
* @param name object name.
* @param <T>
* @return
*/
public <T> T getExtension(Class<T> type, String name) {
for (ExtensionFactory factory : factories) {
T extension = factory.getExtension(type, name);
if (extension != null) {
return extension;
}
}
return null;
}
}
public class SpiExtensionFactory implements ExtensionFactory {
/**
* SPI机制获取type接口扩展实现类
* @param type object type. 必须是接口并且有@SPI注解
* @param name object name.
* @param <T>
* @return
*/
public <T> T getExtension(Class<T> type, String name) {
if (type.isInterface() && type.isAnnotationPresent(SPI.class)) {
ExtensionLoader<T> loader = ExtensionLoader.getExtensionLoader(type);
if (loader.getSupportedExtensions().size() > 0) {
//获取的是接口@Adaptive实现
return loader.getAdaptiveExtension();
}
}
return null;
}
}
public class SpringExtensionFactory implements ExtensionFactory {
private static final Set<ApplicationContext> contexts = new ConcurrentHashSet<ApplicationContext>();
public static void addApplicationContext(ApplicationContext context) {
contexts.add(context);
}
public static void removeApplicationContext(ApplicationContext context) {
contexts.remove(context);
}
@SuppressWarnings("unchecked")
public <T> T getExtension(Class<T> type, String name) {
//从spring容器获取
for (ApplicationContext context : contexts) {
if (context.containsBean(name)) {
Object bean = context.getBean(name);
if (type.isInstance(bean)) {
return (T) bean;
}
}
}
return null;
}
}
3.1. 回过头来,再来看ExtensionLoader.getExtensionLoader(ExtensionFactory.class).getAdaptiveExtension())
/**
* 获取一个SPI扩展接口的有@Adaptive扩展实现类实例(实现类有@Adatptive注解标记的)
* 整体逻辑:
* (1)从缓存中获取,Holder<Object> cachedAdaptiveInstance:持有@Adaptive标记的扩展实现类实例
* (2)若缓存未命中,则创建一个新的实例,并置入缓存cachedAdaptiveInstance
* @return
*/
@SuppressWarnings("unchecked")
public T getAdaptiveExtension() {
//Holder<Object> cachedAdaptiveInstance:持有@Adaptive标记的扩展实现类实例
Object instance = cachedAdaptiveInstance.get();
if (instance == null) {
if(createAdaptiveInstanceError == null) {
synchronized (cachedAdaptiveInstance) {
instance = cachedAdaptiveInstance.get();
if (instance == null) {
try {
//缓存不存在,就创建@Adaptive标记的扩展实现类实例
instance = createAdaptiveExtension();
cachedAdaptiveInstance.set(instance);
} catch (Throwable t) {
createAdaptiveInstanceError = t;
throw new IllegalStateException("fail to create adaptive instance: " + t.toString(), t);
}
}
}
}
else {
throw new IllegalStateException("fail to create adaptive instance: " + createAdaptiveInstanceError.toString(), createAdaptiveInstanceError);
}
}
return (T) instance;
}
/**
* 创建@Adaptive标记的扩展实现类实例
* @return
*/
@SuppressWarnings("unchecked")
private T createAdaptiveExtension() {
try {
//获取@Adaptive标记的扩展实现类Class,通过反射创建实例,同时要走依赖注入流程
//AdaptiveExtensionClass已在SPI文件解析时赋值
return injectExtension((T) getAdaptiveExtensionClass().newInstance());
} catch (Exception e) {
throw new IllegalStateException("Can not create adaptive extenstion " + type + ", cause: " + e.getMessage(), e);
}
}
/**
* 获取@Adaptive标记的扩展实现类Class
* @return
*/
private Class<?> getAdaptiveExtensionClass() {
//如果有必要,触发SPI文件加载流程
//找到@Adaptive标记的扩展实现类Class,赋值给cachedAdaptiveClass
getExtensionClasses();
if (cachedAdaptiveClass != null) {
return cachedAdaptiveClass;
}
//不存在有@Adaptive注解的扩展实现类,那肯定是在待扩展接口方法上
//使用dubbo动态生成生成java类字符串,动态编译生成想要的class
return cachedAdaptiveClass = createAdaptiveExtensionClass();
}
private Class<?> createAdaptiveExtensionClass() {
String code = createAdaptiveExtensionClassCode();
ClassLoader classLoader = findClassLoader();
com.alibaba.dubbo.common.compiler.Compiler compiler = ExtensionLoader.getExtensionLoader(com.alibaba.dubbo.common.compiler.Compiler.class).getAdaptiveExtension();
return compiler.compile(code, classLoader);
}
getAdaptiveExtension()整体执行流程:目前ExtensionFactory接口3个实现类中,只有AdaptiveExtensionFactory类是Adaptive的
- 获取一个SPI扩展接口的有@Adaptive扩展实现类实例(实现类有@Adatptive注解标记的)
- (1)从缓存中获取,Holder cachedAdaptiveInstance:持有@Adaptive标记的扩展实现类实例
- (2)若缓存未命中,则创建一个新的实例,并置入缓存cachedAdaptiveInstance
getAdaptiveExtension()流程其实和getExtension()差不多,如果有必要也需要加载分析SPI文件
4.1. 前边有提到包装类,来看一下包装类(ProtocolFilterWrapper或ProtocolListenerWrapper),dubbo-aop原理就是包装设计模式
/**
* Protocol的包装类
* ListenerProtocol
*
* @author william.liangf
*/
public class ProtocolFilterWrapper implements Protocol {
private final Protocol protocol;
public ProtocolFilterWrapper(Protocol protocol){
if (protocol == null) {
throw new IllegalArgumentException("protocol == null");
}
this.protocol = protocol;
}
public int getDefaultPort() {
return protocol.getDefaultPort();
}
/**
* 实例化过滤器链
* @param invoker
* @param key
* @param group
* @param <T>
* @return
*/
private static <T> Invoker<T> buildInvokerChain(final Invoker<T> invoker, String key, String group) {
Invoker<T> last = invoker;
List<Filter> filters = ExtensionLoader.getExtensionLoader(Filter.class).getActivateExtension(invoker.getUrl(), key, group);
if (filters.size() > 0) {
for (int i = filters.size() - 1; i >= 0; i --) {
final Filter filter = filters.get(i);
final Invoker<T> next = last;
last = new Invoker<T>() {
public Class<T> getInterface() {
return invoker.getInterface();
}
public URL getUrl() {
return invoker.getUrl();
}
public boolean isAvailable() {
return invoker.isAvailable();
}
public Result invoke(Invocation invocation) throws RpcException {
return filter.invoke(next, invocation);
}
public void destroy() {
invoker.destroy();
}
@Override
public String toString() {
return invoker.toString();
}
};
}
}
return last;
}
/**
* 暴露前,执行过滤器链
* @param invoker 服务的执行体
* @param <T>
* @return
* @throws RpcException
*/
public <T> Exporter<T> export(Invoker<T> invoker) throws RpcException {
if (Constants.REGISTRY_PROTOCOL.equals(invoker.getUrl().getProtocol())) {
return protocol.export(invoker);
}
return protocol.export(buildInvokerChain(invoker, Constants.SERVICE_FILTER_KEY, Constants.PROVIDER));
}
/**
* 调用前执行过滤器链
* @param type 服务的类型
* @param url 远程服务的URL地址
* @param <T>
* @return
* @throws RpcException
*/
public <T> Invoker<T> refer(Class<T> type, URL url) throws RpcException {
if (Constants.REGISTRY_PROTOCOL.equals(url.getProtocol())) {
return protocol.refer(type, url);
}
return buildInvokerChain(protocol.refer(type, url), Constants.REFERENCE_FILTER_KEY, Constants.CONSUMER);
}
public void destroy() {
protocol.destroy();
}
}
5.1. 前边有提到@Adaptive注解使用的两种方式,一种是在扩张接口的扩展实现类上标记,另一种是在扩展接口的方法上标记,这两种第1种优先,没有底1种的情况下dubbo动态生成Class,以Protocol为例讲一下另一种
/**
* Protocol. (API/SPI, Singleton, ThreadSafe)
*
* @author william.liangf
*/
@SPI("dubbo")
public interface Protocol {
/**
* 获取缺省端口,当用户没有配置端口时使用。
*
* @return 缺省端口
*/
int getDefaultPort();
/**
* 暴露远程服务:<br>
* 1. 协议在接收请求时,应记录请求来源方地址信息:RpcContext.getContext().setRemoteAddress();<br>
* 2. export()必须是幂等的,也就是暴露同一个URL的Invoker两次,和暴露一次没有区别。<br>
* 3. export()传入的Invoker由框架实现并传入,协议不需要关心。<br>
*
* @param <T> 服务的类型
* @param invoker 服务的执行体
* @return exporter 暴露服务的引用,用于取消暴露
* @throws RpcException 当暴露服务出错时抛出,比如端口已占用
*/
@Adaptive
<T> Exporter<T> export(Invoker<T> invoker) throws RpcException;
/**
* 引用远程服务:<br>
* 1. 当用户调用refer()所返回的Invoker对象的invoke()方法时,协议需相应执行同URL远端export()传入的Invoker对象的invoke()方法。<br>
* 2. refer()返回的Invoker由协议实现,协议通常需要在此Invoker中发送远程请求。<br>
* 3. 当url中有设置check=false时,连接失败不能抛出异常,并内部自动恢复。<br>
*
* @param <T> 服务的类型
* @param type 服务的类型
* @param url 远程服务的URL地址
* @return invoker 服务的本地代理
* @throws RpcException 当连接服务提供方失败时抛出
*/
@Adaptive
<T> Invoker<T> refer(Class<T> type, URL url) throws RpcException;
/**
* 释放协议:<br>
* 1. 取消该协议所有已经暴露和引用的服务。<br>
* 2. 释放协议所占用的所有资源,比如连接和端口。<br>
* 3. 协议在释放后,依然能暴露和引用新的服务。<br>
*/
void destroy();
}
private Class<?> createAdaptiveExtensionClass() {
//生成@Adaptive类源码字符串
String code = createAdaptiveExtensionClassCode();
ClassLoader classLoader = findClassLoader();
//通过SPI获取java编译器
com.alibaba.dubbo.common.compiler.Compiler compiler = ExtensionLoader.getExtensionLoader(com.alibaba.dubbo.common.compiler.Compiler.class).getAdaptiveExtension();
//编译源码返回Class
return compiler.compile(code, classLoader);
}
动态生成的Class,Adpative类在dubbo中非常常用
package com.alibaba.dubbo.rpc;
import com.alibaba.dubbo.common.extension.ExtensionLoader;
public class Protocol$Adpative implements com.alibaba.dubbo.rpc.Protocol {
public void destroy() {
throw new UnsupportedOperationException("method public abstract void com.alibaba.dubbo.rpc.Protocol.destroy() of interface com.alibaba.dubbo.rpc.Protocol is not adaptive method!");
}
public int getDefaultPort() {
throw new UnsupportedOperationException("method public abstract int com.alibaba.dubbo.rpc.Protocol.getDefaultPort() of interface com.alibaba.dubbo.rpc.Protocol is not adaptive method!");
}
public com.alibaba.dubbo.rpc.Invoker refer(java.lang.Class arg0, com.alibaba.dubbo.common.URL arg1) throws com.alibaba.dubbo.rpc.RpcException {
if (arg1 == null) throw new IllegalArgumentException("url == null");
com.alibaba.dubbo.common.URL url = arg1;
String extName = (url.getProtocol() == null ? "dubbo" : url.getProtocol());
if (extName == null)
throw new IllegalStateException("Fail to get extension(com.alibaba.dubbo.rpc.Protocol) name from url(" + url.toString() + ") use keys([protocol])");
com.alibaba.dubbo.rpc.Protocol extension = (com.alibaba.dubbo.rpc.Protocol) ExtensionLoader.getExtensionLoader(com.alibaba.dubbo.rpc.Protocol.class).getExtension(extName);
return extension.refer(arg0, arg1);
}
public com.alibaba.dubbo.rpc.Exporter export(com.alibaba.dubbo.rpc.Invoker arg0) throws com.alibaba.dubbo.rpc.RpcException {
if (arg0 == null) throw new IllegalArgumentException("com.alibaba.dubbo.rpc.Invoker argument == null");
if (arg0.getUrl() == null)
throw new IllegalArgumentException("com.alibaba.dubbo.rpc.Invoker argument getUrl() == null");
com.alibaba.dubbo.common.URL url = arg0.getUrl();
String extName = (url.getProtocol() == null ? "dubbo" : url.getProtocol());
if (extName == null)
throw new IllegalStateException("Fail to get extension(com.alibaba.dubbo.rpc.Protocol) name from url(" + url.toString() + ") use keys([protocol])");
com.alibaba.dubbo.rpc.Protocol extension = (com.alibaba.dubbo.rpc.Protocol) ExtensionLoader.getExtensionLoader(com.alibaba.dubbo.rpc.Protocol.class).getExtension(extName);
return extension.export(arg0);
}
}