文章要點(diǎn)
- 什么是spi
- dubbo為什么實(shí)現(xiàn)自己的spi
- dubbo的adaptive機(jī)制
- dubbo的IOC和AOP
- dubbo動(dòng)態(tài)編譯機(jī)制
- dubbo與spring的融合
一、什么是spi
SPI 全稱為 (Service Provider Interface) 欧芽,是JDK內(nèi)置的一種服務(wù)提供發(fā)現(xiàn)機(jī)制伶跷。SPI是一種動(dòng)態(tài)替換發(fā)現(xiàn)的機(jī)制盛垦。我們經(jīng)常遇到的就是java.sql.Driver接口前普,不同的數(shù)據(jù)庫不同的Driver實(shí)現(xiàn)砸捏。
如何應(yīng)用竟闪?
當(dāng)服務(wù)的提供者提供了一種接口的實(shí)現(xiàn)之后景殷,需要在classpath下的META-INF/services/目錄里創(chuàng)建一個(gè)以服務(wù)接口命名的文件溅呢,這個(gè)文件里的內(nèi)容就是這個(gè)接口的具體的實(shí)現(xiàn)類。當(dāng)程序需要這個(gè)服務(wù)的時(shí)候猿挚,調(diào)用java.util.ServiceLoader加載spi配置文件即可獲取spi文件里所有的實(shí)現(xiàn)類咐旧。
舉例說明
mysql
在mysql-connector-java-5.1.45.jar中,META-INF/services目錄下會(huì)有一個(gè)名字為java.sql.Driver的文件:
com.mysql.jdbc.Driver
com.mysql.fabric.jdbc.FabricMySQLDriver
驅(qū)動(dòng)加載
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();
可參考:spi詳解
二绩蜻、dubbo為什么實(shí)現(xiàn)自己的spi
為什么dubbo要實(shí)現(xiàn)自己的spi铣墨?
- JDK 是加載所有的spi類,沒有用到的會(huì)浪費(fèi)
- JDK spi不支持緩存
- JDK spi通過for循環(huán)進(jìn)行加載办绝,dubbo支持按照key進(jìn)行獲取spi對象
三伊约、dubbo 的adaptive機(jī)制
Adaptive如字面意思,適配的類孕蝉。dubbo的spi入口ExtensionLoader.getExtensionLoader屡律,當(dāng)我們傳入type,ExtensionLoader掃描對應(yīng)的spi文件昔驱,如果類加@Adaptive注解則直接返回疹尾,反之自動(dòng)生成對應(yīng)適配類上忍。
調(diào)用ExtensionLoader的地方有多個(gè)骤肛,下面列兩個(gè)纳本,有興趣的可以自己跟蹤下代碼
//com.alibaba.dubbo.container.Main 啟動(dòng)入口
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();
調(diào)用鏈路
|--ExtensionLoader.getAdaptiveExtension
|----ExtensionLoader.createAdaptiveExtension
|------ExtensionLoader.injectExtension
|--------ExtensionLoader.getAdaptiveExtensionClass
|----------ExtensionLoader.getExtensionClasses
|------------ExtensionLoader.loadExtensionClasses
|--------------ExtensionLoader.loadFile
|----------ExtensionLoader.createAdaptiveExtensionClass
getAdaptiveExtensionClass,獲取Adaptive適配類腋颠,返回 cachedAdaptiveClass繁成,這個(gè)在 spi加載的時(shí)候會(huì)提取出來并緩存到cachedAdaptiveClass,如果沒有Adaptive類則自動(dòng)生成淑玫。
先看下getExtensionClasses調(diào)用的loadExtensionClasses的實(shí)現(xiàn)邏輯
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
加載對應(yīng)路徑下的spi文件里的class并存儲(chǔ)到緩存變量里
加載的路徑
DUBBO_INTERNAL_DIRECTORY = META-INF/dubbo/internal/
DUBBO_DIRECTORY = META-INF/dubbo/
SERVICES_DIRECTORY = META-INF/services/
文件名
目錄 + type.getName();
三個(gè)緩存變量
cachedAdaptiveClass
如果這個(gè)class含有adaptive注解就賦值巾腕,例如ExtensionFactory,而例如Protocol在這個(gè)環(huán)節(jié)是沒有的絮蒿。
cachedWrapperClasses
只有當(dāng)該class無adative注解尊搬,并且構(gòu)造函數(shù)包含目標(biāo)接口(type)類型,例如protocol里面的spi就只有ProtocolFilterWrapper和ProtocolListenerWrapper能命中
cachedActivates
剩下的類土涝,類有Activate注解
cachedNames
剩下的類就存儲(chǔ)在這里
代碼視圖
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參數(shù)的構(gòu)造方法,如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());
}
}
}
}
}
//省略若干代碼
}
經(jīng)過spi文件的加載,對應(yīng)的class都已經(jīng)緩存蜡饵,最后調(diào)用ExtensionLoader.getAdaptiveExtension返回弹渔,getAdaptiveExtension方法會(huì)判斷 cachedAdaptiveInstance
是否為空如果不為空則返回反之則生成對應(yīng)的 Adaptive類,生成邏輯見下方第五小節(jié)溯祸。
四肢专、dubbo 的IOC和AOP
private T createExtension(String name) {
//從緩存里獲取class
Class<?> clazz = getExtensionClasses().get(name);
if (clazz == null) {
throw findException(name);
}
try {
//從緩存獲取class實(shí)例
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進(jìn)行包裝,這里使用到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
實(shí)例對象緩存
getExtension(String name)返回的是 get出來的對象wrapper對象焦辅,例如protocol就是ProtocolFilterWrapper和ProtocolListenerWrapper其中一個(gè)鸟召。
injectExtension(T instance)//dubbo的IOC反轉(zhuǎn)控制,就是從spi或spring 容器里面獲取對象并賦值氨鹏。
IOC
dubbo的IOC反轉(zhuǎn)控制欧募,就是從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) : "";
//獲取對應(yīng)的對象仆抵,這里有SpringExtensionFactory 和 SpiExtensionFactory兩種實(shí)現(xiàn)
//如果SpiExtensionFactory不支持的則通過SpringExtensionFactory 從spring容器中獲取實(shí)例對象
Object object = objectFactory.getExtension(pt, property);
if (object != null) {
//set注入
method.invoke(instance, object);
}
//省略部分代碼
return instance;
}
AOP
AOP的簡單設(shè)計(jì), createExtension的aop代碼實(shí)現(xiàn)
//這里獲取當(dāng)前spi下所有 包裝類型跟继,這里其實(shí)就是一個(gè)裝飾者模式的運(yùn)用,可以參考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的動(dòng)態(tài)編譯
以 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類舔糖,就自動(dòng)生成
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的默認(rèn)協(xié)議是 dubbo
@SPI("dubbo")
public interface Protocol {
只對Protocol帶有 @Adaptive 注解的方法寫入實(shí)現(xiàn)體莺匠,其它方法的實(shí)現(xiàn)則拋出異常金吗,生成的代碼樣例如下
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里的協(xié)議,如果為空則使用默認(rèn)協(xié)議 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);
}
}
最后調(diào)用 JavassistCompiler.compile 方法進(jìn)行編譯旱物,需要將java源碼編譯成二進(jìn)制class并利用classloader加載至內(nèi)存,這樣我們的程序才能調(diào)用這個(gè)類卫袒。
六宵呛、dubbo與spring的融合
容器的啟動(dòng)
com.alibaba.dubbo.container.Main
dubbo啟動(dòng)入口, Container的默認(rèn)策略是spring
spring=com.alibaba.dubbo.container.spring.SpringContainer
main方法的實(shí)現(xiàn)體會(huì)調(diào)用 SpringContainer.start方法夕凝,方法的實(shí)現(xiàn)體就是常規(guī)的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">
<!-- 提供方應(yīng)用信息宝穗,用于計(jì)算依賴關(guān)系 -->
<dubbo:application name="hello-world-app"/>
<!-- 使用multicast廣播注冊中心暴露服務(wù)地址 -->
<dubbo:registry address="zookeeper://127.0.0.1:2181" check="false" client="zkclient" />
<!-- 用dubbo協(xié)議在20880端口暴露服務(wù) -->
<dubbo:protocol name="dubbo" port="20880"/>
<!-- 聲明需要暴露的服務(wù)接口 -->
<dubbo:service interface="com.youzan.dubbo.api.DemoService"
class="com.youzan.dubbo.provider.DemoServiceImpl"/>
</beans>
這是一個(gè)常見的dubbo服務(wù) xml,這些dubbo標(biāo)簽是對spring的拓展码秉。
spring的拓展約定逮矛,需要有三個(gè)文件
dubbo.xsd 定義 dubbo xml標(biāo)簽及xml節(jié)點(diǎn)約定
spring.schemas 定義 namespace和xsd的對應(yīng)關(guān)系
spring.handlers 指定 namespace的xml解析類
spring.handlers的文件內(nèi)容
public 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));
}
}
這里的各個(gè)標(biāo)簽對應(yīng)都有對應(yīng)的 parser,在parse方法里转砖,走的spring的一套橱鹏,將xml信息組裝成BeanDefinition返回,接著由spring容器把對應(yīng)的類進(jìn)行實(shí)例化堪藐。