共计 10839 个字符,预计需要花费 28 分钟才能阅读完成。
Java SPI(Service Provider Interface)
(1)接口
public interface SPIService {public void printService(); | |
} |
(2)接口实现 1
public class SPIServiceImpl implements SPIService {public void printService() {System.out.println("Hello World"); | |
} | |
} |
(3)接口实现 2
public class SPIServiceImpl2 implements SPIService {public void printService() {System.out.println("Hello World2"); | |
} | |
} |
(4)接口实现 2
public class SPIServiceImpl3 implements SPIService {public void printService() {System.out.println("Hello World3"); | |
} | |
} |
(5)在 resource 目录下建立 META-INF/services 目录,建立接口的全路径名文件(这里是 gdut.ff.spi.SPIService),在文件里以分行符分隔接口实现类的全路径名。
(6)Main 方法
import java.util.ServiceLoader; | |
public class SPIServiceMain {public static void main(String[] args) {ServiceLoader<SPIService> serviceLoader = ServiceLoader.load(SPIService.class); | |
for (SPIService spiService:serviceLoader) {spiService.printService(); | |
} | |
} | |
} |
java.util.ServiceLoader 可以获取接口的全部实现,具体调用哪个实现是用户在 META-INF/services 中配置。
Dubbo SPI
(1)在接口上添加注解 @SPI
import org.apache.dubbo.common.extension.SPI; | |
@SPI("spiServiceImpl") | |
public interface SPIService {public void printService(); | |
} |
(2)在 META-INF/dubbo/internal 文件夹下建立全路径名配置文件,内容如下
spiServiceImpl=gdut.ff.spi.SPIServiceImpl
(3)Main 方法: 通过 ExtensionLoader 获取接口 SPIService.class 的默认实现
public class SPIServiceMain {public static void main(String[] args) {SPIService defaultExtension = ExtensionLoader.getExtensionLoader(SPIService.class).getDefaultExtension(); | |
defaultExtension.printService();} | |
} |
Java SPI 和 Dubbo SPI 对比
(1) Java SPI 会一次性实例化所有拓展点的实现,而 Dubbo SPI 并不会立即全部初始化。
(2) Dubbo SPI 实现了 IoC 和 AOP 机制。
(3) Dubbo SPI 兼容 Java SPI 的配置方式和配置内容,在 Dubbo 启动的时候,会扫描 META-INF/services/,META-INF/dubbo/,META-INF/dubbo/internal/ 三个目录
拓展点注解 @SPI
(1)@SPI 可以使用在类、接口和枚举类上。
(2)标志这是 Dubbo SPI 接口。
(3)SPI 注解有一个 value 属性,可以通过这个属性设置这个接口的默认实现类。
@Documented | |
@Retention(RetentionPolicy.RUNTIME) | |
@Target({ElementType.TYPE}) | |
public @interface SPI { | |
/** | |
* 默认实现类名称 | |
*/ | |
String value() default "";} |
拓展点自适应注解 @Adaptive
(1)@Adaptive 注解可以标记在类、接口、枚举和方法上。
(2)使用 @Adaptive 注解,可以动态地通过 URL 中的参数来确定具体使用的实现类,从而解决了自动加载中的实例注入问题。
(3)当传递的参数 URL 没有参数 key 可以匹配 @Adaptive 的 value 数组的某一个值,就会使用 @SPI(“XXX”)默认实现。
(4)当传递的参数 URL 有参数 key 可以匹配 @Adaptive 的 value 数组的某一个值 (顺序是 key 依次匹配),就使用该 key 对应的 value 值。查找该 value 值在配置文件(META-INF/dubbo/internal/ 目录下) 对应的实现类。
(5)当在某个实现类上加了 @Adaptive 注解,优先级最高,无论默认实现 @SPI 的值是什么和 URL 传递了什么参数,都会直接调用带有 @Adaptive 注解的类。
(6)方法级别注解会生成和编译动态实现类,而类级别的注解不会生成动态类。
(7)会缓存两个与 @Adaptive 有关的对象,Adaptive 具体实现类的 Class 类型缓存在 cachedAdaptiveClass 中;Class 的具体实例化对象缓存在 cachedAdaptiveInstance 中。
@SPI("spiServiceImpl") | |
public interface SPIService {@Adaptive({"test"}) | |
public void printService(URL url); | |
} |
spiServiceImpl=gdut.ff.spi.SPIServiceImpl | |
spiServiceImpl2=gdut.ff.spi.SPIServiceImpl2 | |
spiServiceImpl3=gdut.ff.spi.SPIServiceImpl3 |
public class SPIServiceMain {public static void main(String[] args) {SPIService defaultExtension = ExtensionLoader.getExtensionLoader(SPIService.class).getAdaptiveExtension(); | |
// 这里设置 @Adaptive 的参数 test 的值是 spiServiceImpl2,表示调用 gdut.ff.spi.SPIServiceImpl2 | |
URL url = URL.valueOf("file://localhost/hello?test=spiServiceImpl2"); | |
defaultExtension.printService(url); | |
} | |
} | |
输出是:Hello World2 |
(8)如果在多个实现类上面都加了 @Adaptive 注解,会抛出“发现多于一个 Adaptive 类”错误。
拓展点自适应激活注解 @Activate
(1)可以标记在类、枚举、接口和方法上。主要使用在有多个拓展点,需要根据不同的应用场景激活。
ExtensionLoader 工作原理
public class SPIServiceMain {public static void main(String[] args) {URL url = URL.valueOf("file://localhost/hello"); | |
SPIService defaultService = ExtensionLoader.getExtensionLoader(SPIService.class).getExtension("true"); | |
defaultService.printService(url); | |
} | |
} |
(1)getExtension
private final ConcurrentMap<String, Holder<Object>> cachedInstances = new ConcurrentHashMap<String, Holder<Object>>(); | |
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; | |
} |
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, clazz.newInstance()); | |
instance = (T) EXTENSION_INSTANCES.get(clazz); | |
} | |
injectExtension(instance); | |
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); | |
} | |
} |
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; | |
} |
private Map<String, Class<?>> loadExtensionClasses() { | |
// 获取接口上的注解 SPI | |
final SPI defaultAnnotation = type.getAnnotation(SPI.class); | |
if (defaultAnnotation != null) { | |
//@SPI 注解的 value 值 | |
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" + type.getName() | |
+ ":" + Arrays.toString(names)); | |
} | |
if (names.length == 1) cachedDefaultName = names[0]; | |
} | |
} | |
Map<String, Class<?>> extensionClasses = new HashMap<String, Class<?>>(); | |
// META-INF/dubbo/internal/ 接口全路径名 | |
loadDirectory(extensionClasses, DUBBO_INTERNAL_DIRECTORY, type.getName()); | |
// META-INF/dubbo/internal/ 接口全路径名 | |
loadDirectory(extensionClasses, DUBBO_INTERNAL_DIRECTORY, type.getName().replace("org.apache", "com.alibaba")); | |
// META-INF/dubbo/ 接口全路径名 | |
loadDirectory(extensionClasses, DUBBO_DIRECTORY, type.getName()); | |
// META-INF/dubbo/ 接口全路径名 | |
loadDirectory(extensionClasses, DUBBO_DIRECTORY, type.getName().replace("org.apache", "com.alibaba")); | |
// META-INF/services/ 接口全路径名 | |
loadDirectory(extensionClasses, SERVICES_DIRECTORY, type.getName()); | |
// META-INF/services/ 接口全路径名 | |
loadDirectory(extensionClasses, SERVICES_DIRECTORY, type.getName().replace("org.apache", "com.alibaba")); | |
return extensionClasses; | |
} |
private void loadDirectory(Map<String, Class<?>> extensionClasses, String dir, String type) { | |
String fileName = dir + type; | |
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 resourceURL = urls.nextElement(); | |
loadResource(extensionClasses, classLoader, resourceURL); | |
} | |
} | |
} catch (Throwable t) { | |
logger.error("Exception when load extension class(interface:" + | |
type + ", description file:" + fileName + ").", t); | |
} | |
} |
private void loadResource(Map<String, Class<?>> extensionClasses, ClassLoader classLoader, java.net.URL resourceURL) { | |
try { | |
//IO 流读取 META-INF 文件夹的配置文件 | |
BufferedReader reader = new BufferedReader(new InputStreamReader(resourceURL.openStream(), "utf-8")); | |
try { | |
String line; | |
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) {loadClass(extensionClasses, resourceURL, Class.forName(line, true, classLoader), name); | |
} | |
} catch (Throwable t) {IllegalStateException e = new IllegalStateException("Failed to load extension class(interface:" + type + ", class line:" + line + ") in" + resourceURL + ", cause:" + t.getMessage(), t); | |
exceptions.put(line, e); | |
} | |
} | |
} | |
} finally {reader.close(); | |
} | |
} catch (Throwable t) { | |
logger.error("Exception when load extension class(interface:" + | |
type + ", class file:" + resourceURL + ") in" + resourceURL, t); | |
} | |
} |
private void loadClass(Map<String, Class<?>> extensionClasses, java.net.URL resourceURL, Class<?> clazz, String name) throws NoSuchMethodException { | |
// 判断 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."); | |
} | |
// 判断实现类 clazz 是否有 @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 if (isWrapperClass(clazz)) { | |
Set<Class<?>> wrappers = cachedWrapperClasses; | |
if (wrappers == null) {cachedWrapperClasses = new ConcurrentHashSet<Class<?>>(); | |
wrappers = cachedWrapperClasses; | |
} | |
wrappers.add(clazz); | |
} else {clazz.getConstructor(); | |
if (name == null || name.length() == 0) {name = 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) {cachedActivates.put(names[0], activate); | |
} else { | |
// support com.alibaba.dubbo.common.extension.Activate | |
com.alibaba.dubbo.common.extension.Activate oldActivate = clazz.getAnnotation(com.alibaba.dubbo.common.extension.Activate.class); | |
if (oldActivate != null) {cachedActivates.put(names[0], oldActivate); | |
} | |
} | |
// 普通拓展类,缓存起来 | |
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()); | |
} | |
} | |
} | |
} | |
} |
(2)getAdaptiveExtension
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; | |
} |
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 Class<?> getAdaptiveExtensionClass() {getExtensionClasses(); | |
if (cachedAdaptiveClass != null) {return cachedAdaptiveClass;} | |
return cachedAdaptiveClass = createAdaptiveExtensionClass();} |
ExtensionFactory
package org.apache.dubbo.common.extension; | |
@SPI | |
public interface ExtensionFactory {<T> T getExtension(Class<T> var1, String var2); | |
} |
有三种实现:
(1)SpiExtensionFactory
(2)SpringExtensionFactory
(3)AdaptiveExtensionFactory
代码编译器
(1)JDK 编译器 JdkCompiler
(2)Javassist 编译器 JavassistCompiler
(3)Adaptive 编译器 AdaptiveCompiler
参考资料
《深入理解 Apache Dubbo 与实战》
Dubbo SPI 之 Adaptive 详解