dubbo的spi機(jī)制
dubbo的擴(kuò)展點(diǎn)加載機(jī)制源自于java的spi擴(kuò)展機(jī)制。那么,何為java的spi擴(kuò)展機(jī)制?
java的spi擴(kuò)展機(jī)制
作為接口編程的一種典型應(yīng)用,系統(tǒng)在設(shè)計(jì)某個(gè)功能模塊時(shí)(需要其他的框架提供),只定義了接口,而服務(wù)提供者需要根據(jù)spi的相關(guān)規(guī)范,進(jìn)行接口實(shí)現(xiàn)類(lèi)的實(shí)現(xiàn)。而我們的系統(tǒng)不需要重新進(jìn)行編譯或者生成,即可以使用接口的新的實(shí)現(xiàn)類(lèi)。
java的spi的步驟:
- 在META-INF/services/目錄中創(chuàng)建以接口全限定名命名的文件該文件內(nèi)容為Api具體實(shí)現(xiàn)類(lèi)的全限定名
- 使用ServiceLoader類(lèi)動(dòng)態(tài)加載META-INF中的實(shí)現(xiàn)類(lèi)
- 如SPI的實(shí)現(xiàn)類(lèi)為Jar則需要放在主程序classPath中
- Api具體實(shí)現(xiàn)類(lèi)必須有一個(gè)不帶參數(shù)的構(gòu)造方法
具體案例:
https://download.csdn.net/download/andyzhu_2005/10808099
dubbo的spi
dubbo的spi源于java的spi,但是做了如下兩點(diǎn)改進(jìn):
1、java的spi一次性初始化所有的擴(kuò)展實(shí)現(xiàn),比較浪費(fèi)時(shí)間。(這一點(diǎn)不太理解,其實(shí)dubbo中對(duì)于相關(guān)的接口的擴(kuò)展實(shí)現(xiàn),貌似也是一次性加載所有的)
2、dubbo存在接口名字命名的文件是以鍵值對(duì)形式存儲(chǔ)的,可以通過(guò)名字快速尋找,而不需要像java原生的spi,需要通過(guò)iterator.hasNext()迭代尋找
3、擴(kuò)展點(diǎn)自動(dòng)裝配功能(IOC)和aop功能(filter以及l(fā)istener等wrapper)
何為 實(shí)現(xiàn)了ioc及aop功能
就是當(dāng)加載一個(gè)擴(kuò)展點(diǎn)時(shí),會(huì)自動(dòng)的注入這個(gè)擴(kuò)展點(diǎn)所依賴(lài)的其他擴(kuò)展點(diǎn),如果描述不清楚的話,可以看下下面的例子:
接口A,實(shí)現(xiàn)類(lèi)A1,A2
接口B,實(shí)現(xiàn)類(lèi)B1,B2
其中實(shí)現(xiàn)類(lèi)A1含有setB()方法,當(dāng)通過(guò)擴(kuò)展機(jī)制加載A的實(shí)現(xiàn)的時(shí)候,會(huì)自動(dòng)的注入一個(gè)B的實(shí)現(xiàn)類(lèi),但是,此時(shí)不是注入B1,也不是注入B2,而是注入一個(gè)自適應(yīng)的B的實(shí)現(xiàn)類(lèi):B$Adpative,該實(shí)現(xiàn)類(lèi)是動(dòng)態(tài)生成的,能夠根據(jù)參數(shù)的不同,自動(dòng)選擇B1或者B2來(lái)進(jìn)行調(diào)用。
擴(kuò)展點(diǎn)使用單一實(shí)例加載,需要確保線程安全性。?
@Adaptive注解,有兩種注解方式:一種是注解在類(lèi)上,一種是注解在方法上。
注解在類(lèi)上,而且是注解在實(shí)現(xiàn)類(lèi)上,目前dubbo只有AdaptiveCompiler和AdaptiveExtensionFactory類(lèi)上標(biāo)注了此注解,這是些特殊的類(lèi),ExtensionLoader需要依賴(lài)他們工作,所以得使用此方式。
注解在方法上,注解在接口的方法上,除了上面兩個(gè)類(lèi)之外,所有的都是注解在方法上。ExtensionLoader根據(jù)接口定義動(dòng)態(tài)的生成適配器代碼,并實(shí)例化這個(gè)生成的動(dòng)態(tài)類(lèi)。被Adaptive注解的方法會(huì)生成具體的方法實(shí)現(xiàn)。沒(méi)有注解的方法生成的實(shí)現(xiàn)都是拋不支持的操作異常UnsupportedOperationException。被注解的方法在生成的動(dòng)態(tài)類(lèi)中,會(huì)根據(jù)url里的參數(shù)信息,來(lái)決定實(shí)際調(diào)用哪個(gè)擴(kuò)展。
擴(kuò)展點(diǎn)的加載
在dubbo中,正常的spi擴(kuò)展基本都如下:
/這樣使用,先獲取ExtensionLoader實(shí)例,然后加載自適應(yīng)的Protocol擴(kuò)展點(diǎn)
Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension();
//使用
protocol.refer(Class<T> type, URL url));
1、第一步,getExtensionLoader(Protocol.class),根據(jù)要加載的接口Protocol,創(chuàng)建出一個(gè)ExtensionLoader實(shí)例,加載完的實(shí)例會(huì)被緩存起來(lái),下次再加載Protocol的ExtensionLoader的時(shí)候,會(huì)使用已經(jīng)緩存的這個(gè),不會(huì)再新建一個(gè)實(shí)例:
2、getAdaptiveExtension()方法:相當(dāng)于對(duì)于 ExtensionLoader.getExtensionLoader(Protocol.class)的ExtensionLoader實(shí)例,對(duì)相關(guān)的文件路徑下,找到所有的此接口的實(shí)現(xiàn),并實(shí)例化;
3、protocol.refer(Class<T> type, URL url));通過(guò)接口的方法的url,找到protocol的具體實(shí)現(xiàn)名,比如dubbo,從而找到真正的protocol的實(shí)現(xiàn),dubboprotocol的refer,執(zhí)行。
每一個(gè)spi擴(kuò)展(即有@spi注解的接口)都對(duì)應(yīng)著一個(gè)ExtensionLoader,互相獨(dú)立。而每個(gè)ExtensionLoader負(fù)責(zé)加載這個(gè)spi擴(kuò)展下所有的實(shí)現(xiàn)(一次性的)。比如protocol對(duì)應(yīng)的ExtensionLoader。
源碼分析(以dubboprotocol為例):
private static final Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension();
這句代碼就是獲取protocol 的自適應(yīng)實(shí)現(xiàn)。返回的protocol 實(shí)例會(huì)根據(jù)url的protocol的名稱(chēng)來(lái)加載不同的實(shí)現(xiàn)類(lèi)。
ExtensionLoader.getExtensionLoader(Protocol.class)源碼解析
@SuppressWarnings("unchecked")
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;
}
看下面這兩句代碼:
EXTENSION_LOADERS.putIfAbsent(type, new ExtensionLoader<T>(type));
loader = (ExtensionLoader<T>) EXTENSION_LOADERS.get(type);
ExtensionLoader<T> loader = (ExtensionLoader<T>)
將斷點(diǎn)打在 EXTENSION_LOADERS.get(type);上,當(dāng)tpye是protocol時(shí)候,F(xiàn)6單句執(zhí)行。
上面方法中
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);
}
EXTENSION_LOADERS是一個(gè)線程安全的ExtensionLoader的hashmap集合,集合的名就是各個(gè)type,比如com.alibaba.dubbo.rpc.Protocol,com.alibaba.dubbo.common.extension.ExtensionFactory等,都是被@spi注解的接口名稱(chēng)。第一次加載的時(shí)候,loader 為空,則執(zhí)行 EXTENSION_LOADERS.putIfAbsent(type, new ExtensionLoader<T>(type));
關(guān)注 new ExtensionLoader<T>(type)方法,就是獲得這個(gè)type(這里就是protocol)的ExtensionLoader。dubbo中大量的使用了這種緩存技術(shù)。
看ExtensionLoader的構(gòu)造方法。是private的,即只能在類(lèi)里內(nèi)部調(diào)用,
private ExtensionLoader(Class<?> type) {
this.type = type;
//如果type不是ExtensionFactory,則objectFactory 就是ExtensionFactory.class的擴(kuò)展。
objectFactory = (type == ExtensionFactory.class ? null : ExtensionLoader.getExtensionLoader(ExtensionFactory.class).getAdaptiveExtension());
}
這里的objectFactory 可以理解為dubbo的容器,類(lèi)似于spring的beanfactory,主要用于dubbo的ioc功能。后續(xù)再研究。
new ExtensionLoader<T>(type)執(zhí)行完,返回了protocol所屬的ExtensionLoader,主要工作就是獲得了一個(gè)objectFactory。
.getAdaptiveExtension();源碼解析
接下來(lái)執(zhí)行 private static final Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension();的getAdaptiveExtension()方法。
用于獲取protocol的自適應(yīng)類(lèi)。(這些工作都是在ExtensionLoader類(lèi)里執(zhí)行,目前type=protocol)。
public T getAdaptiveExtension() {
Object instance = cachedAdaptiveInstance.get();
//這里雙重的instance == null有點(diǎn)像單例模式的雙重檢測(cè),避免線程不安全
if (instance == null) {
if(createAdaptiveInstanceError == null) {
synchronized (cachedAdaptiveInstance) {
instance = cachedAdaptiveInstance.get();
if (instance == null) {
try {
//instance ==null,進(jìn)入createAdaptiveExtension()
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;
}
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);
}
}
instance為空,進(jìn)入createAdaptiveExtension()方法,創(chuàng)建自適應(yīng)擴(kuò)展實(shí)現(xiàn)。 return injectExtension((T) getAdaptiveExtensionClass().newInstance());先看看getAdaptiveExtensionClass(),根據(jù)名稱(chēng)應(yīng)該是獲取到類(lèi)名,后面的newInstance()是java的根據(jù)類(lèi)名生成實(shí)例的操作。
private Class<?> getAdaptiveExtensionClass() {
getExtensionClasses();
if (cachedAdaptiveClass != null) {
return cachedAdaptiveClass;
}
return cachedAdaptiveClass = createAdaptiveExtensionClass();
}
然后進(jìn)入getExtensionClasses()
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;
}
/**
加載所有的實(shí)現(xiàn)類(lèi)
**/
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) {
//正則表達(dá)式,如果spi注解的名字不止一個(gè)的話報(bào)錯(cuò)
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<?>>();
//把相關(guān)路徑下的類(lèi)(對(duì)于protocol接口而言)全都加載到extensionClasses 中來(lái)
loadFile(extensionClasses, DUBBO_INTERNAL_DIRECTORY);
loadFile(extensionClasses, DUBBO_DIRECTORY);
loadFile(extensionClasses, SERVICES_DIRECTORY);
return extensionClasses;
}
查看loadFile的方法,這個(gè)類(lèi)主要就是把路徑下的下面的protocol的接口實(shí)現(xiàn)類(lèi)全部根據(jù)類(lèi)名通過(guò)反射實(shí)例化
registry=com.alibaba.dubbo.registry.integration.RegistryProtocol
filter=com.alibaba.dubbo.rpc.protocol.ProtocolFilterWrapper
listener=com.alibaba.dubbo.rpc.protocol.ProtocolListenerWrapper
mock=com.alibaba.dubbo.rpc.support.MockProtocol
injvm=com.alibaba.dubbo.rpc.protocol.injvm.InjvmProtocol
dubbo=com.alibaba.dubbo.rpc.protocol.dubbo.DubboProtocol
rmi=com.alibaba.dubbo.rpc.protocol.rmi.RmiProtocol
hessian=com.alibaba.dubbo.rpc.protocol.hessian.HessianProtocol
com.alibaba.dubbo.rpc.protocol.http.HttpProtocol
com.alibaba.dubbo.rpc.protocol.webservice.WebServiceProtocol
thrift=com.alibaba.dubbo.rpc.protocol.thrift.ThriftProtocol
memcached=memcom.alibaba.dubbo.rpc.protocol.memcached.MemcachedProtocol
redis=com.alibaba.dubbo.rpc.protocol.redis.RedisProtocol
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的形式 registry=com.alibaba.dubbo.registry.integration.RegistryProtocol
line = line.trim();
if (line.length() > 0) {
try {
String name = null;
int i = line.indexOf('=');
if (i > 0) {
name = line.substring(0, i).trim();
line = line.substring(i + 1).trim();
}
if (line.length() > 0) {
//返回類(lèi),
Class<?> clazz = Class.forName(line, true, classLoader);
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.");
}
//這里判斷類(lèi)的注解是否有Adaptive.class注解,如果有的話,說(shuō)明這個(gè)類(lèi)就是這個(gè)spi擴(kuò)展的默認(rèn)強(qiáng)制實(shí)現(xiàn)類(lèi)(即不會(huì)根據(jù)url的spi的名稱(chēng)來(lái)找對(duì)應(yīng)的實(shí)現(xiàn)類(lèi),并存入cachedAdaptiveClass 中)
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 {
//判斷這個(gè)類(lèi)有沒(méi)有以protocol接口實(shí)現(xiàn)類(lèi)作為構(gòu)造方法的參數(shù),如果有,就說(shuō)明是wrapper類(lèi),把它放入cachedWrapperClasses 類(lèi)中,比如就是ProtocolFilterWrapper 。如果不是的話,直接進(jìn)入下面的catch塊
clazz.getConstructor(type);
Set<Class<?>> wrappers = cachedWrapperClasses;
if (wrappers == null) {
cachedWrapperClasses = new ConcurrentHashSet<Class<?>>();
wrappers = cachedWrapperClasses;
}
wrappers.add(clazz);
} catch (NoSuchMethodException e) {
//獲得無(wú)參的構(gòu)造方法
clazz.getConstructor();
if (name == null || name.length() == 0) {
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);
}
}
}
String[] names = NAME_SEPARATOR.split(name);
if (names != null && names.length > 0) {
Activate activate = clazz.getAnnotation(Activate.class);
if (activate != null) {
cachedActivates.put(names[0], activate);
}
for (String n : names) {
if (! cachedNames.containsKey(clazz)) {
cachedNames.put(clazz, n);
}
Class<?> c = extensionClasses.get(n);
if (c == null) {
//把類(lèi)放入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()執(zhí)行完, 我們的extensionClasses已經(jīng)存了關(guān)于protocol接口所有的以<名稱(chēng),類(lèi)>的hashmap集合了。下面進(jìn)入createAdaptiveExtensionClass()方法,用于
private Class<?> getAdaptiveExtensionClass() {
getExtensionClasses();
if (cachedAdaptiveClass != null) {
return cachedAdaptiveClass;
}
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);
}
createAdaptiveExtensionClass()方法會(huì)自動(dòng)的拼接一個(gè)關(guān)于protocol接口的自適應(yīng)類(lèi),并會(huì)通過(guò)dubbo的編譯器對(duì)這個(gè)類(lèi)進(jìn)行編譯。生成的類(lèi)如下:
package com.alibaba.dubbo.rpc;
import com.alibaba.dubbo.common.extension.ExtensionLoader;
public class Protocol$Adpative implements com.alibaba.dubbo.rpc.Protocol {
@SuppressWarnings("unchecked")
public com.alibaba.dubbo.rpc.Invoker refer(java.lang.Class arg0, com.alibaba.dubbo.common.URL arg1) {
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);
}
@SuppressWarnings("unchecked")
public com.alibaba.dubbo.rpc.Exporter export(com.alibaba.dubbo.rpc.Invoker arg0) {
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();
//根據(jù)URL配置信息獲取Protocol協(xié)議,默認(rèn)是dubbo
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])");
//根據(jù)協(xié)議名,獲取Protocol的實(shí)現(xiàn)
//獲得Protocol的實(shí)現(xiàn)過(guò)程中,會(huì)對(duì)Protocol先進(jìn)行依賴(lài)注入,然后進(jìn)行Wrapper包裝,最后返回被修改過(guò)的Protocol
//包裝經(jīng)過(guò)了ProtocolFilterWrapper,ProtocolListenerWrapper,RegistryProtocol
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);
}
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!");
}
}
這樣就返回了protocol的自適應(yīng)擴(kuò)展類(lèi),其通過(guò)extName ,獲取對(duì)應(yīng)的實(shí)現(xiàn)類(lèi)
protocol.export(Class<T> type, URL url))源碼解析
,比如我們調(diào)用dubboprotocol的export方法,則 通過(guò)上面的 生成的Protocol$Adpative類(lèi),根據(jù)url中的protocol的具體名字,下面的getExtension(extName)獲取到對(duì)應(yīng)的實(shí)例
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);
看看objectFactory 是什么東西
private ExtensionLoader(Class<?> type) {
this.type = type;
//如果type不是ExtensionFactory,則objectFactory 就是ExtensionFactory.class的擴(kuò)展。
objectFactory = (type == ExtensionFactory.class ? null : ExtensionLoader.getExtensionLoader(ExtensionFactory.class).getAdaptiveExtension());
}
在ExtensionLoader類(lèi)中有一個(gè)參數(shù)是objectFactory ,這個(gè)參數(shù)就是dubbo中的容器。
事實(shí)上,每一個(gè)ExtensionLoader都會(huì)有這么個(gè)objectFactory 。比如,我們?cè)跀帱c(diǎn)調(diào)試的時(shí)候,最先加載spi擴(kuò)展的接口是com.alibaba.dubbo.common.threadpool.ThreadPool,那么在通過(guò)
//這里的tpye=com.alibaba.dubbo.common.threadpool.ThreadPool
private ExtensionLoader(Class<?> type) {
this.type = type;
objectFactory = (type == ExtensionFactory.class ? null : ExtensionLoader.getExtensionLoader(ExtensionFactory.class).getAdaptiveExtension());
}
實(shí)現(xiàn)ThreadPool的spi擴(kuò)展時(shí)候,就會(huì)進(jìn)行ExtensionLoader.getExtensionLoader(ExtensionFactory.class).getAdaptiveExtension())的操作,從而又編程對(duì)ExtensionFactory的spi加載或者加載完成后進(jìn)行獲取。
ExtensionFactory接口的spi擴(kuò)展還是通過(guò)ExtensionLoader來(lái)實(shí)現(xiàn)的。
看一下他的實(shí)現(xiàn)。
在方法
public static <T> ExtensionLoader<T> getExtensionLoader(Class<T> type)
中,如果傳進(jìn)來(lái)的是com.alibaba.dubbo.common.extension.ExtensionFactory,則我們?cè)诔跏蓟?ExtensionLoader(Class<?> type)時(shí)候,objectFactory 為null。(這里的理解是我現(xiàn)在要通過(guò)ExtensionLoader類(lèi)生成objectFactory ,所以ExtensionLoader類(lèi)的構(gòu)造方法中是不會(huì)有objectFactory 這個(gè)實(shí)例的,還沒(méi)有生成嘛)
返回ExtensionLoader實(shí)例后,執(zhí)行g(shù)etAdaptiveExtension()操作,通過(guò)上面的分析,我們先看看ExtensionFactory有幾個(gè)實(shí)現(xiàn)類(lèi)。
adaptive=com.alibaba.dubbo.common.extension.factory.AdaptiveExtensionFactory
spi=com.alibaba.dubbo.common.extension.factory.SpiExtensionFactory
spring=com.alibaba.dubbo.config.spring.extension.SpringExtensionFactory
即有三個(gè)實(shí)現(xiàn)類(lèi),再查看com.alibaba.dubbo.common.extension.factory.AdaptiveExtensionFactory
spi=com.alibaba.dubbo.common.extension.factory.SpiExtensionFactory這個(gè)類(lèi),其類(lèi)上有@Adaptive注解,說(shuō)明這個(gè)類(lèi)是ExtensionFactory的默認(rèn)強(qiáng)制實(shí)現(xiàn)。
public AdaptiveExtensionFactory() {
ExtensionLoader<ExtensionFactory> loader = ExtensionLoader.getExtensionLoader(ExtensionFactory.class);
List<ExtensionFactory> list = new ArrayList<ExtensionFactory>();
for (String name : loader.getSupportedExtensions()) {
list.add(loader.getExtension(name));
}
factories = Collections.unmodifiableList(list);
}
上面方法就是把extension的兩個(gè)spi擴(kuò)展實(shí)現(xiàn)
spi=com.alibaba.dubbo.common.extension.factory.SpiExtensionFactory
spring=com.alibaba.dubbo.config.spring.extension.SpringExtensionFactory
給加載進(jìn)來(lái)。
上面方法中的loader.getExtension(name),(name就是extensionFactory),就是獲得spi擴(kuò)展的具體實(shí)現(xiàn)。這里的實(shí)現(xiàn)是指已經(jīng)通過(guò)newInstance獲得類(lèi)的實(shí)例。
/**
* 返回指定名字的擴(kuò)展。如果指定名字的擴(kuò)展不存在,則拋異常 {@link IllegalStateException}.
*
* @param name
* @return
*/
@SuppressWarnings("unchecked")
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;
}
@SuppressWarnings("unchecked")
private T createExtension(String name) {
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) {
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);
}
}
private T injectExtension(T instance) {
try {
if (objectFactory != null) {
for (Method method : instance.getClass().getMethods()) {
if (method.getName().startsWith("set")
&& method.getParameterTypes().length == 1
&& Modifier.isPublic(method.getModifiers())) {
Class<?> pt = method.getParameterTypes()[0];
try {
String property = method.getName().length() > 3 ? method.getName().substring(3, 4).toLowerCase() + method.getName().substring(4) : "";
Object object = objectFactory.getExtension(pt, property);
if (object != null) {
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;
}
而在之后的方法中會(huì)用到objectFactory.getExtension(pt, property);
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;
}
再看看兩個(gè)spi的具體實(shí)現(xiàn):
第一個(gè)SpiExtensionFactory:
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) {
return loader.getAdaptiveExtension();
}
}
return null;
}
}
上面的方法是如果接口有spi注解,那就返回這個(gè)接口的自適應(yīng)擴(kuò)展實(shí)現(xiàn)。
而SpringExtensionFactory的實(shí)現(xiàn)就是正常的如果這個(gè)接口在spring容器里有,那就從容器中取。
@SuppressWarnings("unchecked")
public <T> T getExtension(Class<T> type, String name) {
for (ApplicationContext context : contexts) {
if (context.containsBean(name)) {
Object bean = context.getBean(name);
if (type.isInstance(bean)) {
return (T) bean;
}
}
}
return null;
}
}
所以,從上面可以看出,objectFactory就是一個(gè)容器,通過(guò)接口名獲得相應(yīng)的實(shí)例。
那么在哪里可以用到呢。dubbo中,可以實(shí)現(xiàn)實(shí)例的依賴(lài)注入功能。在createAdaptiveExtension()方法中,通過(guò)spi擴(kuò)展獲得自適應(yīng)實(shí)現(xiàn)類(lèi)的時(shí)候,前面的injectExtension()方法就是對(duì)實(shí)例中的set方法,進(jìn)行屬性的自動(dòng)加載。
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);
}
}
private T injectExtension(T instance) {
try {
if (objectFactory != null) {
for (Method method : instance.getClass().getMethods()) {
if (method.getName().startsWith("set")
&& method.getParameterTypes().length == 1
&& Modifier.isPublic(method.getModifiers())) {
// pt =interface com.alibaba.dubbo.rpc.Protocol等有spi注解的接口
Class<?> pt = method.getParameterTypes()[0];
try {
//public void com.alibaba.dubbo.rpc.proxy.wrapper.StubProxyFactoryWrapper.setProtocol(com.alibaba.dubbo.rpc.Protocol)
//這里的 method.getName().substring(3, 4)就是p,method.getName().substring(4) 就是rotocol,即把Protocol首字母小寫(xiě),取出來(lái)
String property = method.getName().length() > 3 ? method.getName().substring(3, 4).toLowerCase() + method.getName().substring(4) : "";
Object object = objectFactory.getExtension(pt, property);
if (object != null) {
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;
}