Dubbo源码解析(二)之扩展点(ExtensionLoader)篇

我们在阅读dubbo源代码的时候经常会看到ExtensionLoader这个类的身影,命名上我们就可以看出它是一个扩展的加载器,在分析源码之前,读者可以首先去dubbo的官方文档中看一下关于扩展点加载的介绍,对ExtensionLoader先有一个初步的认识,便于更好的理解源码,下面我们就以Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension();这句代码作为入口,来分析其源码实现:
ExtensionLoader:

public static <T> ExtensionLoader<T> getExtensionLoader(Class<T> type) {
if (type == null)
throw new IllegalArgumentException("Extension type == null");
if (!type.isInterface()) { // type必须是接口
throw new IllegalArgumentException("Extension type(" + type + ") is not interface!");
}
if (!withExtensionAnnotation(type)) { // 必须注解@SPI
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) {
// 缓存中没有则新建ExtensionLoader对象放入缓存
EXTENSION_LOADERS.putIfAbsent(type, new ExtensionLoader<T>(type));
loader = (ExtensionLoader<T>) EXTENSION_LOADERS.get(type);
}
return loader;
}
ExtensionLoader:
public T getAdaptiveExtension() {
// 首先尝试从缓存中获取
Object instance = cachedAdaptiveInstance.get();
if (instance == null) {
if (createAdaptiveInstanceError == null) {
synchronized (cachedAdaptiveInstance) {
// 二次检查
instance = cachedAdaptiveInstance.get();
if (instance == null) {
try {
/* 创建自适应扩展点 */
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;
}
getAdaptiveExtension方法用于获取自适应扩展点,关于自适应扩展点,文章开始给出的官方文档的地址中有详细的解释,不明白的读者可以进行查阅。
ExtensionLoader:
private T createAdaptiveExtension() {
try {
/* 获取自适应扩展点实例,并进行注入 */
return injectExtension((T) getAdaptiveExtensionClass().newInstance());
} catch (Exception e) {
throw new IllegalStateException("Can not create adaptive extension " + type + ", cause: " + e.getMessage(), e);
}
}
ExtensionLoader:
private Class<?> getAdaptiveExtensionClass() {
getExtensionClasses(); /* 获取扩展点class */
if (cachedAdaptiveClass != null) {
// 如果缓存的自适应扩展点class不为null,直接返回
return cachedAdaptiveClass;
}
/* 创建自适应扩展点class并返回 */
return cachedAdaptiveClass = createAdaptiveExtensionClass();
}
ExtensionLoader:
private Map<String, Class<?>> getExtensionClasses() {
// 同样的首先尝试从缓存中获取
Map<String, Class<?>> classes = cachedClasses.get();
if (classes == null) {
synchronized (cachedClasses) {
// double check,二次检查
classes = cachedClasses.get();
if (classes == null) {
/* 加载扩展点class */
classes = loadExtensionClasses();
cachedClasses.set(classes);
}
}
}
return classes;
}
ExtensionLoader:
private Map<String, Class<?>> loadExtensionClasses() {
// 获取@SPI注解信息
final SPI defaultAnnotation = type.getAnnotation(SPI.class);
if (defaultAnnotation != null) {
// 获取默认值
String value = defaultAnnotation.value();
if (value != null && (value = value.trim()).length() > 0) {
String[] names = NAME_SEPARATOR.split(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];
}
}
Map<String, Class<?>> extensionClasses = new HashMap<String, Class<?>>();
/* 加载META-INF/dubbo/internal/、META-INF/dubbo/、META-INF/services/ 三个目录下的文件 */
loadFile(extensionClasses, DUBBO_INTERNAL_DIRECTORY);
loadFile(extensionClasses, DUBBO_DIRECTORY);
loadFile(extensionClasses, SERVICES_DIRECTORY);
return extensionClasses;
}
ExtensionLoader:
private void loadFile(Map<String, Class<?>> extensionClasses, String dir) {
String fileName = dir + type.getName(); // 目录+接口名
try {
Enumeration<java.net.URL> urls;
ClassLoader classLoader = findClassLoader();
// 加载文件资源
if (classLoader != null) {
urls = classLoader.getResources(fileName);
} else {
urls = ClassLoader.getSystemResources(fileName);
}
if (urls != null) {
while (urls.hasMoreElements()) {
java.net.URL url = urls.nextElement();
try {
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) {
// =号前为key
name = line.substring(0, i).trim();
// =号后为value
line = line.substring(i + 1).trim();
}
if (line.length() > 0) {
Class<?> clazz = Class.forName(line, true, classLoader);
// 如果配置的class不是给定接口的实现类,抛出异常
if (!type.isAssignableFrom(clazz)) {
throw new IllegalStateException("Error when load extension class(interface: " +
type + ", class line: " + clazz.getName() + "), class "
+ clazz.getName() + "is not subtype of interface.");
}
// 注解@Adaptive的class为自适应扩展点
if (clazz.isAnnotationPresent(Adaptive.class)) {
if (cachedAdaptiveClass == null) {
// 缓存自适应扩展点类型
cachedAdaptiveClass = clazz;
} else if (!cachedAdaptiveClass.equals(clazz)) {
// 给定接口的自适应扩展点只能有一个
throw new IllegalStateException("More than 1 adaptive class found: "
+ cachedAdaptiveClass.getClass().getName()
+ ", " + clazz.getClass().getName());
}
} else {
try {
// 尝试获取以给定接口为参数的构造方法
clazz.getConstructor(type);
Set<Class<?>> wrappers = cachedWrapperClasses;
if (wrappers == null) {
cachedWrapperClasses = new ConcurrentHashSet<Class<?>>();
wrappers = cachedWrapperClasses;
}
// 添加为wrapper包装类
wrappers.add(clazz);
} catch (NoSuchMethodException e) {
// 没有以给定接口为参数的构造方法则尝试获取默认无参构造方法
clazz.getConstructor();
if (name == null || name.length() == 0) {
/* 如果配置的key为空,则尝试获取class注解中配置的name */
name = findAnnotationName(clazz);
if (name == null || name.length() == 0) {
// 如果注解中无法获取到name则判断配置的class的名称是否大于给定接口的名称并且以给定接口名称为结尾,例如XxxProtocol类和Protocol接口就会满足这个条件
if (clazz.getSimpleName().length() > type.getSimpleName().length()
&& clazz.getSimpleName().endsWith(type.getSimpleName())) {
// 截取配置的class名称转换为小写作为name,例如XxxProtocol --> xxx
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);
}
}
}
String[] names = NAME_SEPARATOR.split(name);
if (names != null && names.length > 0) {
// 注解@Activate的class为自动激活扩展点
Activate activate = clazz.getAnnotation(Activate.class);
if (activate != null) {
// 将name和@Activate注解信息添加到映射缓存
cachedActivates.put(names[0], activate);
}
for (String n : names) {
if (!cachedNames.containsKey(clazz)) {
// 添加配置的扩展点class和name的映射缓存
cachedNames.put(clazz, n);
}
Class<?> c = extensionClasses.get(n);
if (c == null) {
// 添加到参数给定的集合中
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);
}
}
}
} finally {
reader.close();
}
} catch (Throwable t) {
logger.error("Exception when load extension class(interface: " +
type + ", class file: " + url + ") in " + url, t);
}
}
}
} catch (Throwable t) {
logger.error("Exception when load extension class(interface: " +
type + ", description file: " + fileName + ").", t);
}
}
这里又提到了扩展点自动激活的概念,官方文档中同样有详细的说明。我们注意一下wrapper包装类,这里把含有以给定接口为参数的构造方法的类作为了包装类,在实例化扩展点对象时,就会用这些包装类进行包装。
ExtensionLoader:
private String findAnnotationName(Class<?> clazz) {
// 获取class上的@Extension注解信息
com.alibaba.dubbo.common.Extension extension = clazz.getAnnotation(com.alibaba.dubbo.common.Extension.class);
if (extension == null) {
String name = clazz.getSimpleName();
if (name.endsWith(type.getSimpleName())) {
// 这里的截取方式与上文中介绍的方式相同
name = name.substring(0, name.length() - type.getSimpleName().length());
}
// 同样转换为小写返回
return name.toLowerCase();
}
// 注解不为null则直接用注解的value作为name
return extension.value();
}
获取扩展点的class之后,会判断这些扩展点中是否有自适应扩展点,也就是@Adaptive注解的class,如果有,则进行下一步的注入操作,如果没有,会创建自适应扩展点,我们来看这个流程:
ExtensionLoader:
private Class<?> createAdaptiveExtensionClass() {
// 拼接自适应扩展点class的字符串
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); // 编译字符串为class
}
这里createAdaptiveExtensionClassCode方法生成自适应扩展点类的流程我们就不具体的进行分析了,就是一些字符串的拼接操作,官方文档(文档中自适应扩展点部分要仔细阅读,解释了在调用时如何注入自适应扩展点)中给出的类的大致结构如下:

package <扩展点接口所在包>;

public class <扩展点接口名>$Adpative implements <扩展点接口> {
public <有@Adaptive注解的接口方法>(<方法参数>) {
if(是否有URL类型方法参数?) 使用该URL参数
else if(是否有方法类型上有URL属性) 使用该URL属性
# <else 在加载扩展点生成自适应扩展点类时抛异常,即加载扩展点失败!>

if(获取的URL == null) {
throw new IllegalArgumentException("url == null");
   }

根据@Adaptive注解上声明的Key的顺序,从URL获致Value,作为实际扩展点名。
如URL没有Value,则使用缺省扩展点实现。如没有扩展点, throw new IllegalStateException("Fail to get extension");

在扩展点实现调用该方法,并返回结果。
}

public <有@Adaptive注解的接口方法>(<方法参数>) {
throw new UnsupportedOperationException("is not adaptive method!");
}
}

 

我们以Protocol为例来看一下生成的扩展点类的结构:

package com.alibaba.dubbo.rpc;
import com.alibaba.dubbo.common.extension.ExtensionLoader;
public class Protocol$Adaptive 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);
}
}
这里通过调用ExtensionLoader.getExtensionLoader方法来获取扩展点实例,我们来看方法实现:
ExtensionLoader:
public T getExtension(String name) {
if (name == null || name.length() == 0)
throw new IllegalArgumentException("Extension name == null");
if ("true".equals(name)) {
return getDefaultExtension();
}
// 首先尝试从缓存中加载
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) {
/* 创建扩展点实例 */
instance = createExtension(name);
holder.set(instance);
}
}
}
return (T) instance;
}
ExtensionLoader:
private T createExtension(String name) {
// 获取扩展点Class,上文已经分析过
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);
}
injectExtension(instance);
Set < Class << ? >> wrapperClasses = cachedWrapperClasses;
if (wrapperClasses != null && wrapperClasses.size() > 0) {
// 循环包装类集合进行包装
for (Class << ? > wrapperClass : wrapperClasses) {
/* setter方法注入 */
instance = injectExtension((T) wrapperClass.getConstructor(type).newInstance(instance));
}
}
return instance;
} catch (Throwable t) {
throw new IllegalStateException("Extension instance(name: " + name + ", class: " +
type + ") could not be instantiated: " + t.getMessage(), t);
}
}

这里我们看到了包装类的应用,构建好类型字符串之后,需要进行编译,编译器dubbo中给出两个实现,JavassistCompiler和JdkCompiler,从命名上我们就可以看出它们的实现机制,Compiler接口@SPI注解的value为javassist,所以默认为JavassistCompiler。编译的过程这里就不多赘述了,有兴趣的读者可以自行研究它们的编译过程。下面我们来看注入操作:
ExtensionLoader:

private T injectExtension(T instance) {
try {
if (objectFactory != null) {
for (Method method : instance.getClass().getMethods()) {
// 获取setter方法
if (method.getName().startsWith("set")
&& method.getParameterTypes().length == 1
&& Modifier.isPublic(method.getModifiers())) {
Class<?> pt = method.getParameterTypes()[0];
try {
// 截取方法的名称作为属性,例如setDefaultCompiler --> defaultCompiler
String property = method.getName().length() > 3 ? method.getName().substring(3, 4).toLowerCase() + method.getName().substring(4) : "";
// 获取扩展对象作为setter方法的参数
Object object = objectFactory.getExtension(pt, property);
if (object != null) {
method.invoke(instance, object); // 调用setter方法赋值
}
} 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;
}

这里的objectFactory是在构造ExtensionLoader初始化的,objectFactory是ExtensionFactory接口的实例,自适应的ExtensionFactory扩展点为AdaptiveExtensionFactory,AdaptiveExtensionFactory的getExtension方法中会调用另外两个dubbo提供的ExtensionFactory,SpringExtensionFactory和SpiExtensionFactory,通过命名我们就能看出,SpringExtensionFactory是通过获取Spring bean的方式来获取扩展对象,而SpiExtensionFactory就是通过我们本篇文章分析的扩展点的方式来获取扩展对象。

ExtensionLoader还有一些其他的方法,例如getActivateExtension、hasExtension等,他们的实现过程与我们本篇文章分析的内容大同小异,一些关键的操作如获取扩展点、注入等都是复用的相同的方法,这里就不多赘述了。到这里,整个dubbo扩展点ExtensionLoader的源码分析就完成了。

posted @ 2021-09-13 15:05  bluesky1  阅读(254)  评论(1编辑  收藏  举报