代碼入口
ServiceConfig類
private static final Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension();
最終返回的結果:
Protocol$Adaptive
方法調用流程圖
getExtensionLoader源碼
//初始化一個ExtensionLoader
//type=com.alibaba.dubbo.rpc.Protocol
public static <T> ExtensionLoader<T> getExtensionLoader(Class<T> type) {
//type進行合法性校驗,包括是否爲空,是否爲一個接口,以及該接口是否帶有SPI的註解
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!");
}
//private static final ConcurrentMap<Class<?>, ExtensionLoader<?>> EXTENSION_LOADERS = new ConcurrentHashMap<Class<?>, ExtensionLoader<?>>();
//從EXTENSION_LOADERS緩存中取type
//loader = com.alibaba.dubbo.common.extension.ExtensionLoader[com.alibaba.dubbo.rpc.Protocol]
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;
}
private ExtensionLoader(Class<?> type) {
this.type = type;
//新建一個ExtensionFactory, 如果本身該load就是ExtensionFactory類型, 則objectFactory置爲null
objectFactory = (type == ExtensionFactory.class ? null : ExtensionLoader.getExtensionLoader(ExtensionFactory.class).getAdaptiveExtension());
}
AdaptiveExtension源碼
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 {
//先是調用getAdaptiveExtensionClass獲得自適應擴展點的class對象,再進行注入操作
return injectExtension((T) getAdaptiveExtensionClass().newInstance());
} catch (Exception e) {
throw new IllegalStateException("Can't create adaptive extension " + type + ", cause: " + e.getMessage(), e);
}
}
getAdaptiveExtensionClass()方法
private Class<?> getAdaptiveExtensionClass() {
//getAdaptiveExtensionClass 方法同樣包含了三個邏輯,如下:
//1:調用 getExtensionClasses 獲取所有的拓展類
//2:檢查緩存,若緩存不爲空,則返回緩存
//3:若緩存爲空,則調用 createAdaptiveExtensionClass 創建自適應拓展類
//ExtensionLoader的核心部分——getExtensionClasses()函數,
//該函數的作用就是掃描classpath底下的配置文件,加載該interface對應的所有的擴展點,並將擴展點進行分類(Adaptive,Activate),以及生成包裝類等。
//在掃描的過程中,如果發現該擴展類爲Adaptive類型,則將該class緩存到cachedAdaptiveClass中。
//如果所有的擴展類均不是Adaptive類型,則調用createAdaptiveExtensionClass生成一個Adaptive類型的擴展類。
getExtensionClasses();
if (cachedAdaptiveClass != null) {
return cachedAdaptiveClass;
}
//如果在調用後,cachedAdaptiveClass沒有被賦值,則自動生成一個自適應的擴展點
return cachedAdaptiveClass = createAdaptiveExtensionClass();
}
getExtensionClasses()方法
//加載擴展點的實現類
private Map<String, Class<?>> getExtensionClasses() {
//map存儲數據結構:
//com.alibaba.dubbo.rpc.Protocol => [com.itheima.dubbo.DefineProtocol]
//如果cachedClasses緩存中沒有,則調用loadExtensionClasses去加載
Map<String, Class<?>> classes = cachedClasses.get();
if (classes == null) {
synchronized (cachedClasses) {
classes = cachedClasses.get();
if (classes == null) {
classes = loadExtensionClasses();
cachedClasses.set(classes);
}
}
}
return classes;
}
// 此方法已經getExtensionClasses方法同步過。
private Map<String, Class<?>> loadExtensionClasses() {
//type = protocol.class
//得到SPI註解
final SPI defaultAnnotation = type.getAnnotation(SPI.class);
if(defaultAnnotation != null) {
//這裏根據註解的值,緩存default的擴展點
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];
}
}
//調用loadDirectory函數根據不同的路徑去加載擴展點
//loadDirectory函數會去DUBBO_INTERNAL_DIRECTORY、DUBBO_DIRECTORY,和SERVICES_DIRECTORY等六個路徑下去尋找配置文件,
//類似於jdk的SPI中放在META-INF/services目錄下的文件,這裏給出protocol的配置文件com.alibaba.dubbo.rpc.Protocol
Map<String, Class<?>> extensionClasses = new HashMap<String, Class<?>>();
loadFile(extensionClasses, DUBBO_INTERNAL_DIRECTORY);
loadFile(extensionClasses, DUBBO_DIRECTORY);
loadFile(extensionClasses, SERVICES_DIRECTORY);
return extensionClasses;
}
loadFile()的方法
//加載文件
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;
//line = [adaptive=org.apache.dubbo.common.extension.factory.AdaptiveExtensionFactory]
//line = [spi=org.apache.dubbo.common.extension.factory.SpiExtensionFactory]
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) {
name = line.substring(0, i).trim();
line = line.substring(i + 1).trim();
}
if (line.length() > 0) {
Class<?> clazz = Class.forName(line, true, classLoader);
//加載對應的實現類,並且判斷實現類是當前的加載的擴展點的實現
//判斷clazz是否爲type的子類,如果不是,拋異常
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種類的擴展類
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;
}
wrappers.add(clazz);
} catch (NoSuchMethodException e) {
//檢查是否有拷貝構造函數
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種類的class
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) {
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);
}
}
//這個函數非常長,而且各種if else的縮進也很深,大概的處理流程是對配置文件中的各個擴展點進行如下操作
//1. 判斷該擴展點是否是要加載的interface的子類,如果不是則忽略
//2. 如果該class帶有Adaptive的註解,則緩存到cachedAdaptiveClass中
//3. 如果該class具有拷貝構造函數,則緩存到cachedWrapperClasses中
//4. 如果該class帶有Activate註解,則緩存到cachedActivates中
//5. 將所有的擴展點緩存到cachedClasses中
getAdaptiveExtensionClass()方法中的(createAdaptiveExtensionClass()方法)
//創建適配器擴展點的過程(創建一個動態的字節碼文件)
//一個type對應的所有擴展點均已加載完畢,我們再回到getAdaptiveExtensionClass中,看一下如果沒有自適應的擴展點,調用createAdaptiveExtensionClass是如何生成一個自適應的類的。
private Class<?> createAdaptiveExtensionClass() {
//構建自適應拓展代碼
String code = new AdaptiveClassCodeGenerator(type, cachedDefaultName).generate();
ClassLoader classLoader = findClassLoader();
//獲取編譯器實現類
org.apache.dubbo.common.compiler.Compiler compiler = ExtensionLoader.getExtensionLoader(org.apache.dubbo.common.compiler.Compiler.class).getAdaptiveExtension();
//動態編譯字節碼
return compiler.compile(code, classLoader);
}
先調用createAdaptiveExtensionClassCode函數生成一段文本代碼,然後再獲取Compiler類型的擴展點去編譯這段代碼。
Compiler的擴展點加載也是通過ExtensionLoader.getExtensionLoader進行的。
Protocol$Adaptive(String extName = (url.getProtocol() == null ? "dubbo" : url.getProtocol() )可以看出dubbo是默認協議)
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);
}
}
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);
}
}
private T injectExtension(T instance) {
try {
if (objectFactory != null) {
for (Method method : instance.getClass().getMethods()) {
//尋找set方法
if (method.getName().startsWith("set")
&& method.getParameterTypes().length == 1
&& Modifier.isPublic(method.getModifiers())) {
/**
* Check {@link DisableInject} to see if we need auto injection for this property
*/
if (method.getAnnotation(DisableInject.class) != null) {
continue;
}
Class<?> pt = method.getParameterTypes()[0];
try {
String property = method.getName().length() > 3 ? method.getName().substring(3, 4).toLowerCase() + method.getName().substring(4) : "";
//從objectFactory獲取要注入的擴展點 objectFactory = AdaptiveExtensionFactory
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;
}
該方法不僅僅用在自適應擴展點的注入,也適用於其他類型的擴展點,我們來看一下注入的大致流程
1. 遍歷該instance的所有方法,找到以set開頭的方法,準備進行注入。
2. 調用objectFactory.getExtension()方式獲取要注入的實例。
3. 調用method.invoke進行注入。
這裏,我們又看到了前面出現的ExtensionFactory,前文提到每個擴展點的ExtensionLoader實例中均有一個objectFactory來存儲ExtensionFactory實例,並且這個objectFactory也是通過getExtensionLoader方式產生的ExtensionFactory自適應的擴展點
構造方法:
private ExtensionLoader(Class<?> type) {
this.type = type;
objectFactory = (type == ExtensionFactory.class ? null : ExtensionLoader.getExtensionLoader(ExtensionFactory.class).getAdaptiveExtension());
}
@SPI
public interface ExtensionFactory {
/**
* Get extension.
*
* @param type object type.
* @param name object name.
* @return object instance.
*/
<T> T getExtension(Class<T> type, String name);
}
ExtensionFactory擴展點分爲SpiExtensionFactory、AdaptiveExtensionFactory和SpringExtensionFactory三種,下面我們來分析一下AdaptiveExtensionFactory的代碼,看看調用objectFactory.getExtension的時候都發生了什麼。
@Adaptive
public class AdaptiveExtensionFactory implements ExtensionFactory {
private final List<ExtensionFactory> factories;
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);
}
@Override
public <T> T getExtension(Class<T> type, String name) {
//factories = [adaptive=org.apache.dubbo.common.extension.factory.AdaptiveExtensionFactory,spi=org.apache.dubbo.common.extension.factory.SpiExtensionFactory]
for (ExtensionFactory factory : factories) {
T extension = factory.getExtension(type, name);
if (extension != null) {
return extension;
}
}
return null;
}
}
在AdaptiveExtensionFactory的構造函數中,將SpiExtensionFactory和SpringExtensionFactory實例化後存入factories中。在getExtension中,會依次調用SpiExtensionFactory和SpringExtensionFactory的方法來尋找擴展點,找到即返回。
以SpiExtensionFactory爲例來看一下具體的getExtension函數:
public class SpiExtensionFactory implements ExtensionFactory {
@Override
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().isEmpty()) {
return loader.getAdaptiveExtension();
}
}
return null;
}
}
其實就是對相應的type生成對應的ExtensionLoader再找到Adaptive擴展點返回。至此,便完成了一個class實例化後,其內部所有的可注入的變量的注入操作。ExtensionFactory就相當於所有擴展點的工廠,提供相應的接口去取獲取擴展點。
代碼入口:(ExtensionLoader.java)
Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getExtension("myProtocol");
加載所有的擴展點
public T getExtension(String name) {
if (name == null || name.length() == 0)
throw new IllegalArgumentException("Extension name == null");
// 如果name是"true",返回默認擴展點實現
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) {
//如果不是默認實現,則先嚐試從緩存中獲取,如果緩存中沒有,再t通過createExtension方法創建實例,最後再放入緩存。
instance = createExtension(name);
holder.set(instance);
}
}
}
return (T) instance;
}
private T createExtension(String name) {
//從SPI配置文件加載class
Class<?> clazz = getExtensionClasses().get(name);
if (clazz == null) {
throw findException(name);
}
try {
//根據得到class創建實例並緩存。
T instance = (T) EXTENSION_INSTANCES.get(clazz);
if (instance == null) {
EXTENSION_INSTANCES.putIfAbsent(clazz, clazz.newInstance());
instance = (T) EXTENSION_INSTANCES.get(clazz);
}
//依賴注入
injectExtension(instance);
//filter=com.alibaba.dubbo.rpc.protocol.ProtocolFilterWrapper
//listener=com.alibaba.dubbo.rpc.protocol.ProtocolListenerWrapper
//進行包裝
Set<Class<?>> wrapperClasses = cachedWrapperClasses;
if (wrapperClasses != null && !wrapperClasses.isEmpty()) {
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);
}
}
instance = injectExtension((T) wrapperClass.getConstructor(type).newInstance(instance));
ProtocolFilterWrapper類
public <T> Exporter<T> export(Invoker<T> invoker) throws RpcException {
if (Constants.REGISTRY_PROTOCOL.equals(invoker.getUrl().getProtocol())) {
return protocol.export(invoker);
}
return protocol.export(buildInvokerChain(invoker, Constants.SERVICE_FILTER_KEY, Constants.PROVIDER));
}
Protocol.export(invoker),這裏是調用的DubboProtocol的export方法。
private static <T> Invoker<T> buildInvokerChain(final Invoker<T> invoker, String key, String group) {
Invoker<T> last = invoker;
List<Filter> filters = ExtensionLoader.getExtensionLoader(Filter.class).getActivateExtension(invoker.getUrl(), key, group);
if (filters.size() > 0) {
for (int i = filters.size() - 1; i >= 0; i --) {
final Filter filter = filters.get(i);
final Invoker<T> next = last;
last = new Invoker<T>() {
public Class<T> getInterface() {
return invoker.getInterface();
}
public URL getUrl() {
return invoker.getUrl();
}
public boolean isAvailable() {
return invoker.isAvailable();
}
public Result invoke(Invocation invocation) throws RpcException {
return filter.invoke(next, invocation);
}
public void destroy() {
invoker.destroy();
}
@Override
public String toString() {
return invoker.toString();
}
};
}
}
return last;
}