dubbo在整体的架构设计上,都是通过扩展点实现的。
Dubbo扩展点规范
- 如果要扩展自定义的SPI(Service Provider Interface),可以再resources目录下配置三种目录,分别是:META-INF/dubbo/或者META-INF/services或者META-INF/dubbo/internal/
- 文件名与接口名称保持一致,文件内容以key-value形式存在,eg:xxx=com.tutujia.xxx.xxx
- eg:如果要扩展dubbo的一个协议,在META-INF/dubbo/com.alibaba.dubbo.rpc.Protocol这个文件中增加一行自己的扩展,xxx=com.tutujia.xxx.xxxProtocol。在dubbo的配置文件<dubbo:protocol name=“xxx”>.
Dubbo的SPI与Java原生SPI的区别
在Java的SPI中在META-INF/services目录中创建以服务接口命名的文件,用来记录这个接口具体的实现类。利用ServiceLoader去加载被定义的接口或者类。
dubbo中的扩展点(Extension)的SPI做了一些改进:
- dubbo的设计中运用了大量的全局缓存,所有的Extension都缓存在chachedInstances中,该对象类型为ConcurrentMap<String, Holder>
- dubbo的扩展点支持默认实现,比如可以通过ExtensionLoader.getExtensionLoader(Protocol.class).getDefaultExtension()来获取
- Dubbo的扩展点可以动态获取扩展对象,比如通过ExtensionLoader.getExtensionLoader(Protocol.class).getExtension(extName)
- Dubbo的扩展点提供了AOP功能,在cachedWrapperClasses中,在原来的SPI的类上包装了xxxFilterWrapper xxxListnerWrapper
- Dubbo的扩展点提供了IOC功能,通过构造函数注入所需的实例
Dubbo中的ExtensionLoader
在dubbo中,我们通常使用ExtensionLoader.getExtensionLoader(Class type).getAdaptiveExtension()方法获取一个我们制定类型的对象。它也是dubbo扩展点的入口,从下面这一句代码入手ExtensionLoader类
ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension();
首先从缓存EXTENSION_LOADERS中读去的type类型的Loader,如果不存在对应的Loader,则会使用type类型去新new一个ExtensionLoader。缓存EXTENSION_LOADERS对应的数据类型是ConrueentHashMap类型。
public static <T> ExtensionLoader<T> getExtensionLoader(Class<T> type) {
if (type == null) {
throw new IllegalArgumentException("Extension type == null");
}
if (!type.isInterface()) {
throw new IllegalArgumentException("Extension type (" + type + ") is not an interface!");
}
if (!withExtensionAnnotation(type)) {
throw new IllegalArgumentException("Extension type (" + type +
") is not an extension, because it is NOT annotated with @" + SPI.class.getSimpleName() + "!");
}
// 从缓存EXTENSION_LOADERS中取得type。如果为null,则new一个新的ExtensionLoader,并缓存在EXTENSION_LOADERS中。
// 当type类型不为ExtensionLoader类型时,走了一次新的new ExtensionLoader的过程。
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;
}
下面看一下缓存EXTENSION_LOADERS中不存在type对应的ExtensionLoader,进入新new的流程。可以发现ExtensionLoader的构造方法为私有方法,并不暴露给外界去new的机会,只能在内部调用。在调用new ExtensionLoader时,会给type赋值。在给objectFactory赋值时,如果type为ExtensionFactory类型,则值为null。否则会调用getExtensionLoader(ExtensionFactory.class).getAdaptiveExtension()获得一个,这个过程会再次执行ExtensionLoader的构造方法,且此次的type=ExtensionFactory类型,则objectFactory为null。
private ExtensionLoader(Class<?> type) {
this.type = type;
// 如果此时传入的type为ExtensionFactory,则objectFactory为null
// 否则,首先调用ExtensionLoader.getExtensionLoader()得到一个ExtensionLoader实例,其次调用getAdaptiveExtension
objectFactory = (type == ExtensionFactory.class ? null : ExtensionLoader.getExtensionLoader(ExtensionFactory.class).getAdaptiveExtension());
}
获得了一个ExtensionLoader对象后,执行getAdaptiveExtension()方法。首先从缓存cachedAdaptiveInsatance中阐释获取一个instance,如果instance为null,经过双锁检测,调用createAdaptiveExtension()获得一个instance后缓存到cachedAdaptiveInsatance中。ps:cachedAdaptiveInsatance是一个Hodler类型的变量,Hodler的结果很简单,仅有一个object。
@SuppressWarnings("unchecked")
public T getAdaptiveExtension() {
// 先从cachedAdaptiveInstance中活动instance
Object instance = cachedAdaptiveInstance.get();
if (instance == null) {
if (createAdaptiveInstanceError != null) {
throw new IllegalStateException("Failed to create adaptive instance: " +
createAdaptiveInstanceError.toString(),
createAdaptiveInstanceError);
}
synchronized (cachedAdaptiveInstance) {
instance = cachedAdaptiveInstance.get();
if (instance == null) {
try {
instance = createAdaptiveExtension();
// 将得到的extensionFactory缓存到cachedAdaptiveInstance中
cachedAdaptiveInstance.set(instance);
} catch (Throwable t) {
createAdaptiveInstanceError = t;
throw new IllegalStateException("Failed to create adaptive instance: " + t.toString(), t);
}
}
}
}
return (T) instance;
}
下面进入createAdaptiveExtension()方法,方法返回值为泛型,此时为ExtensionFactory类型。该方法执行分为两步,第一步:getAdaptiveExtensionClass().newinstance(),第二步:injectExtension()。
private T createAdaptiveExtension() {
try {
return injectExtension((T) getAdaptiveExtensionClass().newInstance());
} catch (Exception e) {
throw new IllegalStateException("Can't create adaptive extension " + type + ", cause: " + e.getMessage(), e);
}
}
下面进入第一步getAdaptiveExtensionClass()方法。通过getExtensionClasses()获取一个扩展点。如果cachedClasses中尚未缓存,则通过loadExtensionClasses()加载classes。在loadExtensionClasses之前,需要调用cacheDefaultExtensionClasses对type进行处理,如果type类型上标有@SPI注解,如果标有该注解,则尝试设置cachedDefaultName;否则直接返回。通过loadDirectory加载特定目录下的扩展类。
private Class<?> getAdaptiveExtensionClass() {
// 获取一个适配器扩展点类
getExtensionClasses();
// 如果在类上有@Adaptive注解,它会缓存到cacheAdaptiveClass中
if (cachedAdaptiveClass != null) {
return cachedAdaptiveClass;
}
return cachedAdaptiveClass = createAdaptiveExtensionClass();
}
/**
* 从缓存cachedClasses中获取,如果没有经过双锁检测,loadExtensionClasses()获取
*
* @return
*/
private Map<String, Class<?>> getExtensionClasses() {
Map<String, Class<?>> classes = cachedClasses.get();
if (classes == null) {
synchronized (cachedClasses) {
classes = cachedClasses.get();
if (classes == null) {
classes = loadExtensionClasses();
cachedClasses.set(classes);
}
}
}
return classes;
}
/**
* synchronized in getExtensionClasses
* 方法已经在getExtensionClasses中同步过了
* <p>
* 加载DUBBO_INTERNAL_DIRECTORY、DUBBO_DIRECTORY、SERVICES_DIRECTORY目录下的的文件
*/
private Map<String, Class<?>> loadExtensionClasses() {
cacheDefaultExtensionName();
Map<String, Class<?>> extensionClasses = new HashMap<>();
loadDirectory(extensionClasses, DUBBO_INTERNAL_DIRECTORY, type.getName());
loadDirectory(extensionClasses, DUBBO_INTERNAL_DIRECTORY, type.getName().replace("org.apache", "com.alibaba"));
loadDirectory(extensionClasses, DUBBO_DIRECTORY, type.getName());
loadDirectory(extensionClasses, DUBBO_DIRECTORY, type.getName().replace("org.apache", "com.alibaba"));
loadDirectory(extensionClasses, SERVICES_DIRECTORY, type.getName());
loadDirectory(extensionClasses, SERVICES_DIRECTORY, type.getName().replace("org.apache", "com.alibaba"));
return extensionClasses;
}
/**
* extract and cache default extension name if exists
* 获取type上是否打有@SPI的注解标签
* 如果没有,则直接返回
* 如果存在,尝试设置cachedDefaultName值
*/
private void cacheDefaultExtensionName() {
final SPI defaultAnnotation = type.getAnnotation(SPI.class);
if (defaultAnnotation == null) {
return;
}
String value = defaultAnnotation.value();
if ((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];
}
}
}
loadDirectory中会找到classloader,后面会调用loadResource,最后调用loadClass。下面主要看loadClass如何加载类。首先判断clazz上是否有@Adative注解,如果有则直接赋值给cachedAdaptiveClass(ps:volatile Class<?>)。如果类上没有@Adaptive注解,而类具有参数类型为type类型的构造方法,则将class缓存到cachedWrapperClasses中。否则,将clazz缓存值cachedNames和extensionClasses中。
private void loadClass(Map<String, Class<?>> extensionClasses, java.net.URL resourceURL, Class<?> clazz, String name) throws NoSuchMethodException {
if (!type.isAssignableFrom(clazz)) {
throw new IllegalStateException("Error occurred when loading extension class (interface: " +
type + ", class line: " + clazz.getName() + "), class "
+ clazz.getName() + " is not subtype of interface.");
}
// 如果类上打有@Adaptive注解,这直接赋值给cachedAdaptiveClass
if (clazz.isAnnotationPresent(Adaptive.class)) {
cacheAdaptiveClass(clazz);
} else if (isWrapperClass(clazz)) {
// 如果没有@Adaptive注解,判断有没有参数为type的构造方法,如果存在,则将clazz缓存在cachedWrapperClasses中
cacheWrapperClass(clazz);
} else {
// 如果不满足上述两种情况,则判断clazz是否存在构造方法
clazz.getConstructor();
if (StringUtils.isEmpty(name)) {
name = findAnnotationName(clazz);
if (name.length() == 0) {
throw new IllegalStateException("No such extension name for the class " + clazz.getName() + " in the config " + resourceURL);
}
}
// 将clazz缓存至cachedNames
String[] names = NAME_SEPARATOR.split(name);
if (ArrayUtils.isNotEmpty(names)) {
cacheActivateClass(clazz, names[0]);
for (String n : names) {
cacheName(clazz, n);
saveInExtensionClass(extensionClasses, clazz, n);
}
}
}
}
/**
* cache name
*/
private void cacheName(Class<?> clazz, String name) {
if (!cachedNames.containsKey(clazz)) {
cachedNames.put(clazz, name);
}
}
/**
* put clazz in extensionClasses
*/
private void saveInExtensionClass(Map<String, Class<?>> extensionClasses, Class<?> clazz, String name) {
Class<?> c = extensionClasses.get(name);
if (c == null) {
extensionClasses.put(name, clazz);
} else if (c != clazz) {
throw new IllegalStateException("Duplicate extension " + type.getName() + " name " + name + " on " + c.getName() + " and " + clazz.getName());
}
}
现在我们已经拿到了extensionClass,返回上层getAdaptiveExtensionClass()中,继续向下执行。若cachedAdaptiveClass不为null,则直接返回。通过前面的分析,当类上面有@Adaptive注解时,就会缓存到cachedAdaptiveClass。如果为null,则调用createAdaptiveExtensionClass方法生成一个。返回到getAdaptiveExtensionClass()方法中,回到ExtensionLoader的构造方法中,此时objectFactory已经有值了,就是AdaptiveExtensionFactory,返回getExtensionLoader()方法,将得到的ExtensionLoaer实例值缓存至EXTENSION_LOADERS中,此时type=protocol。