SPI机制,即对同一个接口会有不同的实现类,我们可以根据应用场景通过配置来选择使用不同的实现类。在Dubbo中,protocol的选择就是通过@SPI来实现。
其SPI目的是遵守开闭原则的面向对象设计,对于变化点的可扩展性,利用配置式服务发现机制动态加载相关接口实现类。
在分析ReferenceConfig类中,获取相应协议的protocol作为扩展点。协议protocol的选择并没有在代码中显式表现出来。
private static final Protocol refprotocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension();
从如上代码中可以看到,将Protocol.class作为参数传递给了ExtensionLoader的静态方法getExtensionLoader(),得到专门处理Protocol类的ExtensionLoader。我们先来看下其getExtensionLoader()方法。
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 interface!");
}
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;
}
可以看到,传入的类为null或者传入的类不是接口类型都会报错,值得注意的是如果传入的接口未实现@SPI接口,还是会报错。那么能够被ExtensionLoader出来的接口类型都有注解@SPI。
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
public @interface SPI {
/**
* 缺省扩展点名。
*/
String value() default "";
}
我们可以看到Protocol类注解。
@SPI("dubbo")
public interface Protocol {
int getDefaultPort();
@Adaptive
<T> Exporter<T> export(Invoker<T> invoker) throws RpcException;
@Adaptive
<T> Invoker<T> refer(Class<T> type, URL url) throws RpcException;
void destroy();
}
例如Protocol类作为接口也实现了@SPI,默认的value为dubbo,也就是说明在dubbo框架中默认选用dubbo协议。它在配置文件中找到dubbo对应的DubboProtocol,目前来看实现类似于spring的注入。
配置在目录/META_INF/dubbo/internal/com.alibaba.dubbo.rpc.Protocol文件中,文件内容为:
dubbo=com.alibaba.dubbo.rpc.protocol.dubbo.DubboProtocol
http=com.alibaba.dubbo.rpc.protocol.http.HttpProtocol
hessian=com.alibaba.dubbo.rpc.protocol.hessian.HessianProtocol
我们来看具体实现,在传入的类类型检查完毕后,会从以类和类对应的ExtensionLoader对应的键值对的map类型的EXTENSION_LOADERS中去取得相应的ExtensionLoader,如果没取到,则重新调用ExtensionLoader的构造方法生成新的类所对应的ExtensionLoader。
看下ExtensionLoader的构造方法
private ExtensionLoader(Class<?> type) {
this.type = type;
objectFactory = (type == ExtensionFactory.class ? null :
ExtensionLoader.getExtensionLoader(ExtensionFactory.class).getAdaptiveExtension());
}
其构造方法非常简单,将类型存储,其类工厂的获取方法又和ReferenceConfig中的Protocol的选择一样,我们分析完了这儿就同理了。
回到在ReferenceConfig中,在获取到处理Protocol类对应的ExtensionLoader后,调用getAdaptiveExtension()方法获取真正需要拿来使用的具体protocol扩展点的适配类。
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;
}
先从缓存中获取,也就是之前用过该扩展点了,那么直接返回所需的扩展点。但如果是第一次调用,那么通过createAdaptiveExtension()方法,这里有用到双重检查,主要是保证并非安全。
private T createAdaptiveExtension() {
try {
return injectExtension((T) getAdaptiveExtensionClass().newInstance());
} catch (Exception e) {
throw new IllegalStateException("Can not create adaptive extenstion " + type + ", cause: " + e.getMessage(), e);
}
}
其中getAdaptiveExtensionClass通过getExtensionClasses()方法,获取扩展点的类集合。
private Class<?> getAdaptiveExtensionClass() {
getExtensionClasses();
if (cachedAdaptiveClass != null) {
return cachedAdaptiveClass;
}
return cachedAdaptiveClass = createAdaptiveExtensionClass();
}
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;
}
还是有缓存,如果第一次调用,则通过loadExtensionClasses()方法加载所需要的扩展点的类。
// 此方法已经getExtensionClasses方法同步过。
private Map<String, Class<?>> loadExtensionClasses() {
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<?>>();
loadFile(extensionClasses, DUBBO_INTERNAL_DIRECTORY);
loadFile(extensionClasses, DUBBO_DIRECTORY);
loadFile(extensionClasses, SERVICES_DIRECTORY);
return extensionClasses;
}
在这里如果@SPI的value值存在,就将cacheDefaultName设为value的值。
接下来load以下三个目录的文件。
private static final String SERVICES_DIRECTORY = "META-INF/services/";
private static final String DUBBO_D