Dubbo作为开源框架,必须要提供很多的可扩展点。Dubbo的扩展点加载采用了微核心插件式的开发模式,它是比较符合OCP原则。
微核心
由一个插件生命周期管理容器,构成微核心, 核心不包括任何功能,这样可以确保所有功能都能被替换,并且框架实现的功能,扩展者也一定能做到,以保证平等对待第三方。因此Dubbo框架自身的功能也采用了插件的方式来实现,不采用任何硬编码。
通常微核心都会采用Factory,IoC,OSGi等方式管理插件生命周期,为了减少对spring的依赖,Dubbo放弃使用spring的IoC容器,而采用了Factory方式来管理插件。
JDK SPI机制
JDK标准的SPI(Service Provider Interface)扩展点发现机制,即我们定义了服务接口标准,厂商提供具体的接口实现,JDK通过ServiceLoader类实现SPI机制的服务查找功能,下面是简单示例:
首先定义接口
package com.example;
public interface DemoService{
String sayHello();
}
ServiceLoader会遍历所有jar查找META-INF/services/com.example.DemoService文件
A厂商实现
package com.a.example;
public class DemoServiceAImpl implements DemoService{
public String sayHello(){
return "hello 我是厂商A";
}
}
在A厂商提供的jar包中的META-INF/services/com.example.DemoService文件内容为:com.a.example.DemoServiceAImpl
B厂商实现
package com.b.example;
public class DemoServiceBImpl implements DemoService{
public String sayHello(){
return "hello 我是厂商B";
}
}
在B厂商提供的jar包中的META-INF/services/com.example.DemoService文件内容为:com.b.example.DemoServiceBImpl
ServiceLoader.load(DemoService.class)读取厂商A、B提供jar包中文件,获取接口DemoServie的所有实现类
基于SPI思想的Dubbo扩展点机制
Dubbo根据JDK SPI机制的思想实现了自己的扩展点机制,位于com.alibaba.dubbo.common.extension包下的ExtensionLoader是Dubbo扩展点机制的核心,相当于JDK SPI中的ServiceLoader。
下面我们以Protocol接口实现类的加载为例,来解析ExtensionLoader的加载过程。
Protocol接口
package com.alibaba.dubbo.rpc;
@SPI("dubbo")
public interface Protocol {
int getDefaultPort();
@Adaptive
Exporter export(Invoker invoker) throws RpcException;
@Adaptive
Invoker refer(Class type, URL url) throws RpcException;
void destroy();
}
打开dubbo源码,在dubbo-rpc-api模块的META-INF/dubbo/internal/目录下,会发现com.alibaba.dubbo.rpc.Protocol文件,其内容为:
filter=com.alibaba.dubbo.rpc.protocol.ProtocolFilterWrapper
listener=com.alibaba.dubbo.rpc.protocol.ProtocolListenerWrapper
mock=com.alibaba.dubbo.rpc.support.MockProtocol
而dubbo-rpc-default模块的META-INF/dubbo/internal/com.alibaba.dubbo.rpc.Protocol文件内容为:
dubbo=com.alibaba.dubbo.rpc.protocol.dubbo.DubboProtocol
ProtocolFilterWrapper、ProtocolListenerWrapper、MockProtocol、DubboProtocol都是Protocol接口的实现类,com.alibaba.dubbo.rpc.Protocol文件的格式为:配置名=扩展实现类全限定名,多个实现类用换行符分隔。
那么ExtensionLoader是如何加载Protocol接口的这些实现类的呢?
在ServiceConfig类中有这样一行代码
private static final Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension();
ExtensionLoader.getExtensionLoader方法
public static ExtensionLoader getExtensionLoader(Class type) {
if (type == null)
throw new IllegalArgumentException("Extension type == null");
if(!type.isInterface()) {
throw new IllegalArgumentException("Extension type(" + type + ") is not interface!");
}
if(!withExtensionAnnotation(type)) {
throw new IllegalArgumentException("Extension type(" + type +
") is not extension, because WITHOUT @" + SPI.class.getSimpleName() + " Annotation!");
}
ExtensionLoader loader = (ExtensionLoader) EXTENSION_LOADERS.get(type);
if (loader == null) {
EXTENSION_LOADERS.putIfAbsent(type, new ExtensionLoader<T>(type));
loader = (ExtensionLoader) EXTENSION_LOADERS.get(type);
}
return loader;
}
未完待续……