概述
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详解
最后
以上就是冷静月饼为你收集整理的Dubbo拓展点加载机制的全部内容,希望文章能够帮你解决Dubbo拓展点加载机制所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复