Dubbo剖析-SPI機制
文章要點:
1、什麼是SPi
2、Dubbo為什麼要實現自己的SPi
3、Dubbo的IOC和AOP
4、Dubbo的Adaptive機制
5、Dubbo動態編譯機制
6、Dubbo與Spring的融合
一、什麼是SPI
SPI 全稱為 (Service Provider Interface) ,是JDK內建的一種服務提供發現機制。SPI是一種動態替換髮現的機制。我們經常遇到的就是java.sql.Driver介面,不同的資料庫不同的Driver實現。
如何應用?
當服務的提供者提供了一種介面的實現之後,需要在classpath下的META-INF/services/目錄裡建立一個以服務介面命名的檔案,這個檔案裡的內容就是這個介面的具體的實現類。當程式需要這個服務的時候,調 java.util.ServiceLoader載入spi配置檔案即可獲取spi檔案裡所有的實現類。
舉例說明
mysql
在mysql-connector-java-5.1.45.jar中,META-INF/services目錄下會有一個名字為java.sql.Driver的檔案:
com.mysql.jdbc.Driver
com.mysql.fabric.jdbc.FabricMySQLDriver
驅動載入
DriverManager
static { loadInitialDrivers(); println("JDBC DriverManager initialized"); }//loadInitialDrivers AccessController.doPrivileged(new PrivilegedAction<Void>() { public Void run() { ServiceLoader<Driver> loadedDrivers = ServiceLoader.load(Driver.class); Iterator<Driver> driversIterator = loadedDrivers.iterator();
二、dubbo為什麼實現自己的spi
//com.alibaba.dubbo.container.Main 啟動入口 private static final ExtensionLoader<Container> loader = ExtensionLoader.getExtensionLoader(Container.class);
//com.alibaba.dubbo.config.ServiceConfig private static final Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension();
呼叫鏈路
|--ExtensionLoader.getAdaptiveExtension|----ExtensionLoader.createAdaptiveExtension
|------ExtensionLoader.injectExtension
|--------ExtensionLoader.getAdaptiveExtensionClass
|----------ExtensionLoader.getExtensionClasses
|------------ExtensionLoader.loadExtensionClasses
|--------------ExtensionLoader.loadFile
|----------ExtensionLoader.createAdaptiveExtensionClass getAdaptiveExtensionClass,獲取Adaptive適配類,返回 cachedAdaptiveClass,這個在 spi載入的時候會提取出來並快取到cachedAdaptiveClass,如果沒有Adaptive類則自動生成 先看下getExtensionClasses呼叫的loadExtensionClasses的實現邏輯
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]; } } //將所有的spi快取到extensionClasses Map<String, Class<?>> extensionClasses = new HashMap<String, Class<?>>(); loadFile(extensionClasses, DUBBO_INTERNAL_DIRECTORY); loadFile(extensionClasses, DUBBO_DIRECTORY); loadFile(extensionClasses, SERVICES_DIRECTORY); return extensionClasses; }
loadFile
載入對應路徑下的spi檔案裡的class並存儲到快取變數裡
載入的路徑
DUBBO_INTERNAL_DIRECTORY = META-INF/dubbo/internal/ DUBBO_DIRECTORY = META-INF/dubbo/ SERVICES_DIRECTORY = META-INF/services/
檔名
目錄 + type.getName();
三個快取變數
cachedAdaptiveClass
如果這個class含有adaptive註解就賦值,例如ExtensionFactory,而例如Protocol在這個環節是沒有的。
cachedWrapperClasses
只有當該class無adative註解,並且建構函式包含目標介面(type)型別,例如protocol裡面的spi就只有ProtocolFilterWrapper和ProtocolListenerWrapper能命中
cachedActivates
剩下的類,類有Activate註解
cachedNames
剩下的類就儲存在這裡
程式碼檢視
private void loadFile(Map<String, Class<?>> extensionClasses, String dir) { //省略若干程式碼 Class<?> clazz = Class.forName(line, true, classLoader); //檢視類或方法是否包含Adaptive註解,如:AdaptiveExtensionFactory 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 { //判斷該類是否有type引數的構造方法,如ProtocolFilterWrapper,ProtocolListenerWrapper clazz.getConstructor(type); Set<Class<?>> wrappers = cachedWrapperClasses; if (wrappers == null) { cachedWrapperClasses = new ConcurrentHashSet<Class<?>>(); wrappers = cachedWrapperClasses; } //新增到 cachedWrapperClasses wrappers.add(clazz); } catch (NoSuchMethodException e) { clazz.getConstructor(); if (name == null || name.length() == 0) { //spi沒有key的情況下, 讀取註解名 name = findAnnotationName(clazz); if (name == null || name.length() == 0) { if (clazz.getSimpleName().length() > type.getSimpleName().length() && clazz.getSimpleName().endsWith(type.getSimpleName())) { //讀取 simpleName的一部分作為name 如 com.alibaba.dubbo.rpc.protocol.http.HttpProtocol 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 activate = clazz.getAnnotation(Activate.class); if (activate != null) { cachedActivates.put(names[0], activate); } for (String n : names) { if (!cachedNames.containsKey(clazz)) { //上面的邏輯如果都沒有符合的,加入到 cachedNames 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()); } } } } } //省略若干程式碼 }經過spi檔案的載入,對應的class都已經快取,最後呼叫ExtensionLoader.getAdaptiveExtension返回,getAdaptiveExtension方法會判斷
cachedAdaptiveInstance
是否為空如果不為空則返回反之則生成對應的 Adaptive類,生成邏輯見下方第五小節。
四、
dubbo 的IOC和AOP
private T createExtension(String name) { //從快取裡獲取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, (T) clazz.newInstance()); instance = (T) EXTENSION_INSTANCES.get(clazz); } //模仿spring做的IOC注入 injectExtension(instance); Set<Class<?>> wrapperClasses = cachedWrapperClasses; if (wrapperClasses != null && wrapperClasses.size() > 0) { for (Class<?> wrapperClass : wrapperClasses) { //對instance進行包裝,這裡使用到aop 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); } }
createExtension
從cachedClasses 獲得class名
EXTENSION_INSTANCES
例項物件快取
getExtension(String name)返回的是 get出來的物件wrapper物件,例如protocol就是ProtocolFilterWrapper和ProtocolListenerWrapper其中一個。
injectExtension(T instance)//dubbo的IOC反轉控制,就是從spi或spring 容器裡面獲取物件並賦值
IOC dubbo的IOC反轉控制,就是從spi和spring裡面提取物件賦值。|--injectExtension(T instance)
|----objectFactory.getExtension(pt, property)
|------SpiExtensionFactory.getExtension(type, name)
|--------ExtensionLoader.getExtensionLoader(type)
|--------loader.getAdaptiveExtension()
|------SpringExtensionFactory.getExtension(type, name)
|--------context.getBean(name)
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())) { Class<?> pt = method.getParameterTypes()[0]; try { String property = method.getName().length() > 3 ? method.getName().substring(3, 4).toLowerCase() + method.getName().substring(4) : ""; //獲取對應的物件,這裡有SpringExtensionFactory 和 SpiExtensionFactory兩種實現 //如果SpiExtensionFactory不支援的則通過SpringExtensionFactory 從spring容器中獲取例項物件 Object object = objectFactory.getExtension(pt, property); if (object != null) { //set注入 method.invoke(instance, object); } //省略部分程式碼 return instance; }
AOP
AOP的簡單設計, createExtension的aop程式碼實現
//這裡獲取當前spi下所有 包裝型別,這裡其實就是一個裝飾者模式的運用,可以參考ProtocolFilterWrapper Set<Class<?>> wrapperClasses = cachedWrapperClasses; if (wrapperClasses != null && wrapperClasses.size() > 0) { for (Class<?> wrapperClass : wrapperClasses) { //將instance裝飾完成後返回 instance = injectExtension((T) wrapperClass.getConstructor(type).newInstance(instance)); } } 。
五、dubbo的動態編譯
以 Protocol的spi 舉例子
com.alibaba.dubbo.config.ServiceConfig private static final Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension();
|--ExtensionLoader.getAdaptiveExtensionClass |----ExtensionLoader.createAdaptiveExtensionClass |------ExtensionLoader.createAdaptiveExtensionClassCode
private Class<?> getAdaptiveExtensionClass() { getExtensionClasses(); //如果快取裡有 Adaptive類則直接返回 if (cachedAdaptiveClass != null) { return cachedAdaptiveClass; } //如果沒有Adaptive類,就自動生成 return cachedAdaptiveClass = createAdaptiveExtensionClass(); } private Class<?> createAdaptiveExtensionClass() { //生成類 程式碼文字 String code = createAdaptiveExtensionClassCode(); ClassLoader classLoader = findClassLoader(); //獲取Compiler的spi 類 com.alibaba.dubbo.common.compiler.Compiler compiler = ExtensionLoader.getExtensionLoader(com.alibaba.dubbo.common.compiler.Compiler.class).getAdaptiveExtension(); //編譯程式碼 default=javassist return compiler.compile(code, classLoader); }
createAdaptiveExtensionClassCode
主要生成 Protocol 的 Adaptive類java程式碼,Protocol的預設協議是 dubbo
@SPI("dubbo") public interface Protocol {
只對Protocol帶有 @Adaptive 註解的方法寫入實現體,其它方法的實現則丟擲異常,生成的程式碼樣例如下
package com.alibaba.dubbo.rpc; import com.alibaba.dubbo.common.extension.ExtensionLoader; public class Protocol$Adpative 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.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(); //提取url裡的協議,如果為空則使用預設協議 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])"); 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 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); }
最後呼叫 JavassistCompiler.compile 方法進行編譯,需要將java原始碼編譯成二進位制class並利用classloader載入至記憶體,這樣我們的程式才能呼叫這個類。
六、dubbo與spring的融合
容器的啟動
com.alibaba.dubbo.container.Main
dubbo啟動入口, Container的預設策略是spring
spring=com.alibaba.dubbo.container.spring.SpringContainer
main方法的實現體會呼叫 SpringContainer.start方法,方法的實現體就是常規的spring容器使用姿勢
public void start() { String configPath = ConfigUtils.getProperty(SPRING_CONFIG); if (configPath == null || configPath.length() == 0) { configPath = DEFAULT_SPRING_CONFIG; } context = new ClassPathXmlApplicationContext(configPath.split("[,\\s]+")); context.start(); }
dubbo schema<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:dubbo="http://code.alibabatech.com/schema/dubbo" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd"> <!-- 提供方應用資訊,用於計算依賴關係 --> <dubbo:application name="hello-world-app"/> <!-- 使用multicast廣播註冊中心暴露服務地址 --> <dubbo:registry address="zookeeper://127.0.0.1:2181" check="false" client="zkclient" /> <!-- 用dubbo協議在20880埠暴露服務 --> <dubbo:protocol name="dubbo" port="20880"/> <!-- 宣告需要暴露的服務介面 --> <dubbo:service interface="com.youzan.dubbo.api.DemoService" class="com.youzan.dubbo.provider.DemoServiceImpl"/> </beans> 這是一個常見的dubbo服務 xml,這些dubbo標籤是對spring的拓展。
spring的拓展約定,需要有三個檔案
dubbo.xsd 定義 dubbo xml標籤及xml節點約定
spring.schemas 定義 namespace和xsd的對應關係
spring.handlers 指定 namespace的xml解析類
spring.handlers的檔案內容
http://code.alibabatech.com/schema/dubbo=com.alibaba.dubbo.config.spring.schema.DubboNamespaceHandlerpublic class DubboNamespaceHandler extends NamespaceHandlerSupport { static { Version.checkDuplicate(DubboNamespaceHandler.class); } public void init() { registerBeanDefinitionParser("application", new DubboBeanDefinitionParser(ApplicationConfig.class, true)); registerBeanDefinitionParser("module", new DubboBeanDefinitionParser(ModuleConfig.class, true)); registerBeanDefinitionParser("registry", new DubboBeanDefinitionParser(RegistryConfig.class, true)); registerBeanDefinitionParser("monitor", new DubboBeanDefinitionParser(MonitorConfig.class, true)); registerBeanDefinitionParser("provider", new DubboBeanDefinitionParser(ProviderConfig.class, true)); registerBeanDefinitionParser("consumer", new DubboBeanDefinitionParser(ConsumerConfig.class, true)); registerBeanDefinitionParser("protocol", new DubboBeanDefinitionParser(ProtocolConfig.class, true)); registerBeanDefinitionParser("service", new DubboBeanDefinitionParser(ServiceBean.class, true)); registerBeanDefinitionParser("reference", new DubboBeanDefinitionParser(ReferenceBean.class, false)); registerBeanDefinitionParser("annotation", new DubboBeanDefinitionParser(AnnotationBean.class, true)); } }
這裡的各個標籤對應都有對應的 parser,在parse方法裡,走的spring的一套,將xml資訊組裝成BeanDefinition返回,接著由spring容器把對應的類進行例項化。