1. 首先是主程序類(lèi)com.alibaba.dubbo.common.Main,成員變量如下:
public static final String CONTAINER_KEY = "dubbo.container";
public static final String SHUTDOWN_HOOK_KEY = "dubbo.shutdown.hook";
private static final Logger logger = LoggerFactory.getLogger(Main.class);
private static final ExtensionLoader<Container> loader = ExtensionLoader.getExtensionLoader(Container.class); //靜態(tài)代碼中初始化容器的ExtensionLoader
private static final ReentrantLock LOCK = new ReentrantLock();
private static final Condition STOP;
static {
STOP = LOCK.newCondition();
}
public static void main(String[] args) {
try {
if (args == null || args.length == 0) {
String config = ConfigUtils.getProperty("dubbo.container", loader.getDefaultExtensionName());
args = Constants.COMMA_SPLIT_PATTERN.split(config);
}
final List<Container> containers = new ArrayList();
for(int i = 0; i < args.length; ++i) {
containers.add(loader.getExtension(args[i]));
}
logger.info("Use container type(" + Arrays.toString(args) + ") to run dubbo serivce.");
if ("true".equals(System.getProperty("dubbo.shutdown.hook"))) {
Runtime.getRuntime().addShutdownHook(new Thread("dubbo-container-shutdown-hook") {
public void run() {
Iterator i$ = containers.iterator();
while(i$.hasNext()) {
Container container = (Container)i$.next();
try {
container.stop();
Main.logger.info("Dubbo " + container.getClass().getSimpleName() + " stopped!");
} catch (Throwable var8) {
Main.logger.error(var8.getMessage(), var8);
}
try {
Main.LOCK.lock();
Main.STOP.signal();
} finally {
Main.LOCK.unlock();
}
}
}
});
}
Iterator i$ = containers.iterator();
while(i$.hasNext()) {
Container container = (Container)i$.next();
container.start();
logger.info("Dubbo " + container.getClass().getSimpleName() + " started!");
}
System.out.println((new SimpleDateFormat("[yyyy-MM-dd HH:mm:ss]")).format(new Date()) + " Dubbo service server started!");
} catch (RuntimeException var10) {
var10.printStackTrace();
logger.error(var10.getMessage(), var10);
System.exit(1);
}
try {
LOCK.lock();
STOP.await();
} catch (InterruptedException var8) {
logger.warn("Dubbo service server stopped, interrupted by other thread!", var8);
} finally {
LOCK.unlock();
}
}
可以看到Dubbo啟動(dòng)時(shí)主要做了以下的事情:
- 從main方法參數(shù)或者配置文件的dubbo.container屬性中取出容器名稱(chēng)數(shù)組
- 使用靜態(tài)代碼中已經(jīng)初始化好的ExtensionLoader<Container>加載所有容器
- 如果配置中啟用了dubbo.shutdown.hook,Dubbo會(huì)使用JRE的addShutdownHook鉤子綁定新線(xiàn)程,在這個(gè)線(xiàn)程中配合信號(hào)量同步坤按,實(shí)現(xiàn)了kill命令優(yōu)雅停機(jī)
- 逐個(gè)啟動(dòng)容器
- 阻塞等待停機(jī)信號(hào)量
2. 接下來(lái)我們看擴(kuò)展加載器com.alibaba.dubbo.common.extension.ExtensionLoader類(lèi):
private static final Logger logger = LoggerFactory.getLogger(ExtensionLoader.class);
//JavaSPI路徑
private static final String SERVICES_DIRECTORY = "META-INF/services/";
//Dubbo外部SPI路徑
private static final String DUBBO_DIRECTORY = "META-INF/dubbo/"; private static final String DUBBO_INTERNAL_DIRECTORY = "META-INF/dubbo/internal/";
//Dubbo內(nèi)部SPI路徑
private static final Pattern NAME_SEPARATOR = Pattern.compile("\\s*[,]+\\s*");
//擴(kuò)展類(lèi)的ExtensionLoader集合
private static final ConcurrentMap<Class<?>, ExtensionLoader<?>> EXTENSION_LOADERS = new ConcurrentHashMap();
//擴(kuò)展類(lèi)的實(shí)例集合
private static final ConcurrentMap<Class<?>, Object> EXTENSION_INSTANCES = new ConcurrentHashMap();
//要被擴(kuò)展的接口類(lèi)
private final Class<?> type;
//用于IOC注入其他擴(kuò)展類(lèi)實(shí)例的擴(kuò)展對(duì)象工廠
private final ExtensionFactory objectFactory;
//loadExtension或者loadClass的時(shí)候緩存的擴(kuò)展類(lèi)名,用于快速獲取擴(kuò)展類(lèi)對(duì)應(yīng)的字符串名
private final ConcurrentMap<Class<?>, String> cachedNames = new ConcurrentHashMap();
//loadExtensionClasses時(shí)初始化的Holder吃型,里面是一個(gè)HashMap前联,保存擴(kuò)展類(lèi)Class的容器
private final Holder<Map<String, Class<?>>> cachedClasses = new Holder();
//用于緩存各個(gè)擴(kuò)展類(lèi)的Activate注解
private final Map<String, Activate> cachedActivates = new ConcurrentHashMap();
//用于緩存已經(jīng)加載的擴(kuò)展類(lèi)的實(shí)例
private final ConcurrentMap<String, Holder<Object>> cachedInstances = new ConcurrentHashMap();
//用于緩存適配類(lèi)的實(shí)例(每個(gè)ExtensionLoader只有一個(gè))
private final Holder<Object> cachedAdaptiveInstance = new Holder();
//緩存適配類(lèi)功戚,主要用于在并發(fā)操作下保證適配類(lèi)的唯一性
private volatile Class<?> cachedAdaptiveClass = null;
//緩存的默認(rèn)擴(kuò)展類(lèi)的名稱(chēng)
private String cachedDefaultName;
private volatile Throwable createAdaptiveInstanceError;
//一個(gè)緩存了所有包裝類(lèi)的ConcurrentHashSet
private Set<Class<?>> cachedWrapperClasses;
private Map<String, IllegalStateException> exceptions = new ConcurrentHashMap();
getExtensionLoader類(lèi)方法從EXTENSION_LOADERS中獲取指定類(lèi)的EXTENSION_LOADERS,不存在則調(diào)用構(gòu)造函數(shù)創(chuàng)建似嗤。
public static <T> ExtensionLoader<T> getExtensionLoader(Class<T> type) {
if (type == null) {
throw new IllegalArgumentException("Extension type == null");
} else if (!type.isInterface()) {
throw new IllegalArgumentException("Extension type(" + type + ") is not interface!");
} else if (!withExtensionAnnotation(type)) {
throw new IllegalArgumentException("Extension type(" + type + ") is not extension, because WITHOUT @" + SPI.class.getSimpleName() + " Annotation!");
} else {
ExtensionLoader<T> loader = (ExtensionLoader)EXTENSION_LOADERS.get(type);
if (loader == null) {
//雖然一般不會(huì)出現(xiàn)并發(fā)創(chuàng)建同一個(gè)類(lèi)的ExtensionLoader的情況,但是出現(xiàn)時(shí)這里會(huì)重復(fù)創(chuàng)建多個(gè)實(shí)例烁落,造成資源浪費(fèi)
EXTENSION_LOADERS.putIfAbsent(type, new ExtensionLoader(type));
loader = (ExtensionLoader)EXTENSION_LOADERS.get(type);
}
return loader;
}
}
構(gòu)造函數(shù)里會(huì)保存當(dāng)前的擴(kuò)展類(lèi)類(lèi)型乘粒,同時(shí)對(duì)ExtensionFactory自身之外的其他類(lèi)調(diào)用getAdaptiveExtension方法獲取對(duì)應(yīng)的適配類(lèi)。
private ExtensionLoader(Class<?> type) {
this.type = type;
this.objectFactory = type == ExtensionFactory.class ? null : (ExtensionFactory)getExtensionLoader(ExtensionFactory.class).getAdaptiveExtension();
}
以下就是獲取擴(kuò)展點(diǎn)適配類(lèi)的調(diào)用鏈伤塌,而加載擴(kuò)展點(diǎn)實(shí)例的過(guò)程則從getExtension開(kāi)始灯萍。
public T getAdaptiveExtension() {
Object instance = this.cachedAdaptiveInstance.get();
if (instance == null) {
if (this.createAdaptiveInstanceError != null) {
throw new IllegalStateException("fail to create adaptive instance: " + this.createAdaptiveInstanceError.toString(), this.createAdaptiveInstanceError);
}
Holder var2 = this.cachedAdaptiveInstance;
synchronized(this.cachedAdaptiveInstance) {
instance = this.cachedAdaptiveInstance.get();
if (instance == null) {
try {
instance = this.createAdaptiveExtension();
this.cachedAdaptiveInstance.set(instance);
} catch (Throwable var5) {
this.createAdaptiveInstanceError = var5;
throw new IllegalStateException("fail to create adaptive instance: " + var5.toString(), var5);
}
}
}
}
return instance;
}
private T createAdaptiveExtension() {
try {
return this.injectExtension(this.getAdaptiveExtensionClass().newInstance());
} catch (Exception var2) {
throw new IllegalStateException("Can not create adaptive extension " + this.type + ", cause: " + var2.getMessage(), var2);
}
}
/*
@Adaptive注解在類(lèi)上:代表人工實(shí)現(xiàn),實(shí)現(xiàn)一個(gè)裝飾類(lèi)(設(shè)計(jì)模式中的裝飾模式)每聪,它主要作用于固定已知類(lèi)旦棉,
目前整個(gè)系統(tǒng)只有2個(gè),AdaptiveCompiler药薯、AdaptiveExtensionFactory绑洛。
為什么AdaptiveCompiler這個(gè)類(lèi)是固定已知的?因?yàn)檎麄€(gè)框架僅支持Javassist和JdkCompiler童本。
為什么AdaptiveExtensionFactory這個(gè)類(lèi)是固定已知的真屯?因?yàn)檎麄€(gè)框架僅支持2個(gè)objFactory,一個(gè)是spi,另一個(gè)是spring
*/
private Class<?> getAdaptiveExtensionClass() {
//先加載擴(kuò)展類(lèi),如果擴(kuò)展類(lèi)里已經(jīng)有@Adaptive的實(shí)現(xiàn)類(lèi)穷娱,那么會(huì)加載并存入cachedAdaptiveClass绑蔫,否則Dubbo會(huì)調(diào)用createAdaptiveExtensionClass用字節(jié)碼引擎動(dòng)態(tài)生成
this.getExtensionClasses();
return this.cachedAdaptiveClass != null ? this.cachedAdaptiveClass : (this.cachedAdaptiveClass = this.createAdaptiveExtensionClass());
}
private Class<?> createAdaptiveExtensionClass() {
String code = this.createAdaptiveExtensionClassCode();
ClassLoader classLoader = findClassLoader();
Compiler compiler = (Compiler)getExtensionLoader(Compiler.class).getAdaptiveExtension();
return compiler.compile(code, classLoader);
}
private String createAdaptiveExtensionClassCode() {
//這里用StringBuilder拼出了擴(kuò)展類(lèi)的代碼,比較冗長(zhǎng)鄙煤,故此處省略
}
private T injectExtension(T instance) {
try {
if (this.objectFactory != null) {
Method[] arr$ = instance.getClass().getMethods();
int len$ = arr$.length;
for(int i$ = 0; i$ < len$; ++i$) {
Method method = arr$[i$];
if (method.getName().startsWith("set") && method.getParameterTypes().length == 1 && Modifier.isPublic(method.getModifiers()) && method.getAnnotation(DisableInject.class) == null) {
Class pt = method.getParameterTypes()[0];
try {
String property = method.getName().length() > 3 ? method.getName().substring(3, 4).toLowerCase() + method.getName().substring(4) : "";
Object object = this.objectFactory.getExtension(pt, property);
if (object != null) {
method.invoke(instance, object);
}
} catch (Exception var9) {
logger.error("fail to inject via method " + method.getName() + " of interface " + this.type.getName() + ": " + var9.getMessage(), var9);
}
}
}
}
} catch (Exception var10) {
logger.error(var10.getMessage(), var10);
}
return instance;
}
public T getExtension(String name) {
if (name != null && name.length() != 0) {
if ("true".equals(name)) {
return this.getDefaultExtension();
} else {
Holder<Object> holder = (Holder)this.cachedInstances.get(name);
if (holder == null) {
this.cachedInstances.putIfAbsent(name, new Holder());
holder = (Holder)this.cachedInstances.get(name);
}
Object instance = holder.get();
if (instance == null) {
synchronized(holder) {
instance = holder.get();
if (instance == null) {
instance = this.createExtension(name);
holder.set(instance);
}
}
}
return instance;
}
} else {
throw new IllegalArgumentException("Extension name == null");
}
private T createExtension(String name) {
Class<?> clazz = (Class)this.getExtensionClasses().get(name);
if (clazz == null) {
throw this.findException(name);
} else {
try {
T instance = EXTENSION_INSTANCES.get(clazz);
if (instance == null) {
EXTENSION_INSTANCES.putIfAbsent(clazz, clazz.newInstance());
instance = EXTENSION_INSTANCES.get(clazz);
}
this.injectExtension(instance);
Set<Class<?>> wrapperClasses = this.cachedWrapperClasses;
Class wrapperClass;
if (wrapperClasses != null && !wrapperClasses.isEmpty()) {
for(Iterator i$ = wrapperClasses.iterator(); i$.hasNext(); instance = this.injectExtension(wrapperClass.getConstructor(this.type).newInstance(instance))) {
wrapperClass = (Class)i$.next();
}
}
return instance;
} catch (Throwable var7) {
throw new IllegalStateException("Extension instance(name: " + name + ", class: " + this.type + ") could not be instantiated: " + var7.getMessage(), var7);
}
}
}
private Map<String, Class<?>> getExtensionClasses() {
Map<String, Class<?>> classes = (Map)this.cachedClasses.get();
if (classes == null) {
Holder var2 = this.cachedClasses;
synchronized(this.cachedClasses) {
classes = (Map)this.cachedClasses.get();
if (classes == null) {
classes = this.loadExtensionClasses();
this.cachedClasses.set(classes);
}
}
}
return classes;
}
private Map<String, Class<?>> loadExtensionClasses() {
SPI defaultAnnotation = (SPI)this.type.getAnnotation(SPI.class);
if (defaultAnnotation != null) {
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 " + this.type.getName() + ": " + Arrays.toString(names));
}
if (names.length == 1) {
this.cachedDefaultName = names[0];
}
}
}
Map<String, Class<?>> extensionClasses = new HashMap();
this.loadDirectory(extensionClasses, "META-INF/dubbo/internal/");
this.loadDirectory(extensionClasses, "META-INF/dubbo/");
this.loadDirectory(extensionClasses, "META-INF/services/");
return extensionClasses;
}
private void loadDirectory(Map<String, Class<?>> extensionClasses, String dir) {
String fileName = dir + this.type.getName();
try {
ClassLoader classLoader = findClassLoader();
Enumeration urls;
if (classLoader != null) {
urls = classLoader.getResources(fileName);
} else {
urls = ClassLoader.getSystemResources(fileName);
}
if (urls != null) {
while(urls.hasMoreElements()) {
java.net.URL resourceURL = (java.net.URL)urls.nextElement();
this.loadResource(extensionClasses, classLoader, resourceURL);
}
}
} catch (Throwable var7) {
logger.error("Exception when load extension class(interface: " + this.type + ", description file: " + fileName + ").", var7);
}
}
private void loadResource(Map<String, Class<?>> extensionClasses, ClassLoader classLoader, java.net.URL resourceURL) {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(resourceURL.openStream(), "utf-8"));
String line;
try {
while((line = reader.readLine()) != null) {
int ci = line.indexOf(35);
if (ci >= 0) {
line = line.substring(0, ci);
}
line = line.trim();
if (line.length() > 0) {
try {
String name = null;
int i = line.indexOf(61);
if (i > 0) {
name = line.substring(0, i).trim();
line = line.substring(i + 1).trim();
}
if (line.length() > 0) {
this.loadClass(extensionClasses, resourceURL, Class.forName(line, true, classLoader), name);
}
} catch (Throwable var13) {
IllegalStateException e = new IllegalStateException("Failed to load extension class(interface: " + this.type + ", class line: " + line + ") in " + resourceURL + ", cause: " + var13.getMessage(), var13);
this.exceptions.put(line, e);
}
}
}
} finally {
reader.close();
}
} catch (Throwable var15) {
logger.error("Exception when load extension class(interface: " + this.type + ", class file: " + resourceURL + ") in " + resourceURL, var15);
}
}
private void loadClass(Map<String, Class<?>> extensionClasses, java.net.URL resourceURL, Class<?> clazz, String name) throws NoSuchMethodException {
if (!this.type.isAssignableFrom(clazz)) {
throw new IllegalStateException("Error when load extension class(interface: " + this.type + ", class line: " + clazz.getName() + "), class " + clazz.getName() + "is not subtype of interface.");
} else {
if (clazz.isAnnotationPresent(Adaptive.class)) {
if (this.cachedAdaptiveClass == null) {
this.cachedAdaptiveClass = clazz;
} else if (!this.cachedAdaptiveClass.equals(clazz)) {
throw new IllegalStateException("More than 1 adaptive class found: " + this.cachedAdaptiveClass.getClass().getName() + ", " + clazz.getClass().getName());
}
} else if (this.isWrapperClass(clazz)) {
Set<Class<?>> wrappers = this.cachedWrapperClasses;
if (wrappers == null) {
this.cachedWrapperClasses = new ConcurrentHashSet();
wrappers = this.cachedWrapperClasses;
}
wrappers.add(clazz);
} else {
clazz.getConstructor();
if (name == null || name.length() == 0) {
name = this.findAnnotationName(clazz);
if (name.length() == 0) {
throw new IllegalStateException("No such extension name for the class " + clazz.getName() + " in the config " + resourceURL);
}
}
String[] names = NAME_SEPARATOR.split(name);
if (names != null && names.length > 0) {
Activate activate = (Activate)clazz.getAnnotation(Activate.class);
if (activate != null) {
this.cachedActivates.put(names[0], activate);
}
String[] arr$ = names;
int len$ = names.length;
for(int i$ = 0; i$ < len$; ++i$) {
String n = arr$[i$];
if (!this.cachedNames.containsKey(clazz)) {
this.cachedNames.put(clazz, n);
}
Class<?> c = (Class)extensionClasses.get(n);
if (c == null) {
extensionClasses.put(n, clazz);
} else if (c != clazz) {
throw new IllegalStateException("Duplicate extension " + this.type.getName() + " name " + n + " on " + c.getName() + " and " + clazz.getName());
}
}
}
}
}
}
總結(jié)這段代碼晾匠,可以發(fā)現(xiàn):
- 幾乎所有的Dubbo類(lèi)都是從SPI機(jī)制加載來(lái)的
- 最先被加載的擴(kuò)展類(lèi)是ExtensionFactory,然后是Compiler梯刚,接著是其適配類(lèi),最后才是Container
- IOC注入的實(shí)現(xiàn)在方法injectExtension中
- AOP機(jī)制是通過(guò)包裝類(lèi)來(lái)實(shí)現(xiàn)的薪寓,而Dubbo判斷是否為包裝類(lèi)的標(biāo)準(zhǔn)是是否有帶被包裝類(lèi)參數(shù)的構(gòu)造函數(shù)
private boolean isWrapperClass(Class<?> clazz) {
try {
clazz.getConstructor(this.type);
return true;
} catch (NoSuchMethodException var3) {
return false;
}
}
- 動(dòng)態(tài)類(lèi)的本質(zhì)是可以做到一個(gè)SPI中的不同的Adaptive方法可以去調(diào)不同的SPI實(shí)現(xiàn)類(lèi)去處理亡资。使得程序的靈活性大大提高澜共。這才是整套SPI設(shè)計(jì)的一個(gè)精華之所在
此外對(duì)于集合類(lèi)擴(kuò)展點(diǎn),比如:Filter, InvokerListener, ExportListener, TelnetHandler, StatusChecker等锥腻, @Adaptive可以同時(shí)加載多個(gè)實(shí)現(xiàn)嗦董,此時(shí),可以用自動(dòng)激活來(lái)簡(jiǎn)化配置
public List<T> getActivateExtension(URL url, String[] values, String group) {
List<T> exts = new ArrayList();
List<String> names = values == null ? new ArrayList(0) : Arrays.asList(values);
String name;
if (!((List)names).contains("-default")) {
this.getExtensionClasses();
Iterator i$ = this.cachedActivates.entrySet().iterator();
while(i$.hasNext()) {
Entry<String, Activate> entry = (Entry)i$.next();
name = (String)entry.getKey();
Activate activate = (Activate)entry.getValue();
if (this.isMatchGroup(group, activate.group())) {
T ext = this.getExtension(name);
if (!((List)names).contains(name) && !((List)names).contains("-" + name) && this.isActive(activate, url)) {
exts.add(ext);
}
}
}
Collections.sort(exts, ActivateComparator.COMPARATOR);
}
List<T> usrs = new ArrayList();
for(int i = 0; i < ((List)names).size(); ++i) {
name = (String)((List)names).get(i);
if (!name.startsWith("-") && !((List)names).contains("-" + name)) {
if ("default".equals(name)) {
if (!usrs.isEmpty()) {
exts.addAll(0, usrs);
usrs.clear();
}
} else {
T ext = this.getExtension(name);
usrs.add(ext);
}
}
}
if (!usrs.isEmpty()) {
exts.addAll(usrs);
}
return exts;
}
實(shí)際和AdaptiveExtension一樣在解析時(shí)瘦黑,如果有Activate注解就會(huì)放到cachedActivates里京革。
以dubbo中的filter為例子,ProtocolFilterWrapper中的代碼幸斥,調(diào)用getActivateExtension方法獲得激活的filters匹摇,然后依次執(zhí)行,所謂的集合類(lèi)的擴(kuò)展點(diǎn)其實(shí)dubbo自身代碼已經(jīng)決定了的甲葬,調(diào)用形式不同而已
private static <T> Invoker<T> buildInvokerChain(final Invoker<T> invoker, String key, String group) {
Invoker<T> last = invoker;
// 獲取配置的filters
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;
}
3. 其他
對(duì)比Java SPI:
*不會(huì)在應(yīng)用程序啟動(dòng)時(shí)加載所有擴(kuò)展點(diǎn)實(shí)例
*可以使用注解指定要加載的實(shí)例
*如果加載失敗會(huì)拋出可識(shí)別可追蹤的異常
*支持IOC和AOP機(jī)制廊勃,同時(shí)兼容Spring Bean
不同方式配置SPI實(shí)現(xiàn)類(lèi)的優(yōu)先級(jí):
實(shí)現(xiàn)類(lèi)Adaptive注解 > URL參數(shù) > SPI注解