• Dubbo-SPI机制


    1、Java的SPI机制

    SPI的全称是Service Provider Interface,是JDK内置的动态加载实现扩展点的机制,通过SPI可以动态获取接口的实现类,属于一种设计理念。

    系统设计的各个抽象,往往有很多不同的实现方案,在面向的对象的设计里,一般推荐模块之间基于接口编程,模块之间不对实现类进行硬编码。如果代码中引用了特定的实现类,那么就违反了可插拔的原则。为了进行实现的替换,需要对代码进行修改。需要一种服务发现机制,以实现在模块装配时无需在程序中动态指定。最常见的使用案例有JDBC、Dubbo和Spring。

    笔者在代码中最常用的就是将策略设计模式+SPI进行组合,不直接对接口的实现类进行代码的硬编,可以根据业务的实际使用选择对应的实现类。

    SPI由三个组件构成,Service、Service Provider以及ServiceLoader,下面是一个简单例子:

    1. // 1、使用SPI时先定义好接口
    2. package com.theone.feather
    3. public interface SendService {
    4. String say();
    5. }
    6. // 2、创建实现类
    7. package com.theone.feather;
    8. public class HelloSendService implements SendService {
    9. @Override
    10. public String say() {
    11. return "Hello SPI";
    12. }
    13. }
    14. // 3、在classpath下创建META-INF/services目录,添加文件com.theone.feather.SendService
    15. // 文件名要和接口全路径一样, 里面内容填写实现类的全路径,每个路径各占一行
    16. // 4、通过ServiceLoader调用
    17. @SpringBootApplication
    18. public class TheOneApplication implements CommandLineRunner {
    19. public static void main(String[] args) {
    20. SpringApplication.run(TheOneApplication.class, args);
    21. }
    22. @Override
    23. public void run(String... args) throws Exception {
    24. ServiceLoader loader = ServiceLoader.load(SendService.class);
    25. for(SendService sendService : loader) {
    26. System.out.println(sendService.say());
    27. }
    28. }
    29. }

    从例子也可以看出,传统的SPI迭代时会遍历所有的实现,需要定制化能够做到根据条件自动加载某个实现。

    2、Dubbo的SPI机制

    在聊Dubbo的SPI机制的时候,需要说下开闭原则,开闭原则就是指对扩展开放,修改关闭,尽量通过扩展软件的模块、类、方法,来实现功能的变化,而不是通过修改已有的代码来完成。这样做就可以大大降低因为修改代码而给程序带来的出错率。

    对于Dubbo而言,涉及到服务的RPC调用以及服务治理相关的功能需要抽象出来,而对于具体的实现开放出来,由用户去根据自身业务需要随意扩展(例如下图中各个功能的扩展)。

    所以在Dubbo中,会经常看到下面的逻辑,分别是自适应扩展点、指定名称的扩展点、激活扩展点

    1. ExtensionLoader.getExtensionLoader(xxx.class).getAdaptiveExtension();
    2. ExtensionLoader.getExtensionLoader(xxx.class).getExtension(name);
    3. ExtensionLoader.getExtensionLoader(xxx.class).getActivateExtension(url, key);

    比如在Protocol的获取中,会有

    1. Protocol protocol = ExtensionLoader
    2. .getExtensionLoader(Protocol.class)
    3. .getAdaptiveExtension();

    Dubbo根据你的相关配置,找到具体的Protocol实现类,并实例化具体的对象。所以总结来说,Extension就是指某个功能的扩展实现,可能是Dubbo自带的,也可能是业务自己实现的。

    正常来说,我们用SPI都是把接口的实现的全路径写在文件里面,解析出来之后再通过反射的方式去实例化这个类,然后将这个类放在集合里面存储起来。Dubbo也是这样的操作,而且它还是实现了IOC和AOP的功能。IOC 就是说如果这个扩展类依赖其他属性,Dubbo 会自动的将这个属性进行注入。这个功能如何实现了?一个常见思路是获取这个扩展类的 setter 方法,调用 setter 方法进行属性注入。AOP 指的是什么了?这个说的是 Dubbo 能够为扩展类注入其包装类。比如 DubboProtocol 是 Protocol 的扩展类,ProtocolListenerWrapper 是 DubboProtocol 的包装类。

    下文介绍时,每个功能会用扩展点指代,而对应的实现则是扩展来指代。

    3、Dubbo SPI的实现

    在了解Dubbo的SPI机制之前,有几个注解我们要先了解下

    3.1、@SPI注解

    @SPI注解用于标记一个扩展点接口,该注解提供了扩展点的默认实现已经作用域。

    1. @Documented
    2. @Retention(RetentionPolicy.RUNTIME)
    3. @Target({ElementType.TYPE})
    4. public @interface SPI {
    5. /**
    6. * 默认扩展点实现名
    7. */
    8. String value() default "";
    9. /**
    10. * 扩展点的作用域
    11. */
    12. ExtensionScope scope() default ExtensionScope.APPLICATION;
    13. }

    Dubbo的除了和java原生的spi一样,文件名是接口名之外,内容上支持两种类型的格式

    1. // 第一种格式和Java的SPI一样
    2. com.foo.XxxProtocol
    3. com.foo.YyyProtocol
    4. // 第二种支持key-value的形式,其中key是扩展点实现的名称
    5. xxx=com.foo.XxxProtocol
    6. yyy=com.foo.YyyProtocol
    7. zzz,default=com.foo.ZzzProtocol

    3.2、@Activate注解

    @Activate的作用是用于特定条件下的激活,用户通过group和value配置激活条件,@Activate标记的扩展点实现在满足某个条件时会被会激活并且实例化。也就是自适应扩展类的使用场景,比如我们有需求,在调用某一个方法时,基于参数选择调用到不同的实现类。和工厂方法有些类似,基于不同的参数,构造出不同的实例对象。 在 Dubbo 中实现的思路和这个差不多,不过 Dubbo 的实现更加灵活,它的实现和策略模式有些类似。每一种扩展类相当于一种策略,基于 URL 消息总线,将参数传递给 ExtensionLoader,通过 ExtensionLoader 基于参数加载对应的扩展类,实现运行时动态调用到目标实例上。

    3.3、ExtensionAccessor

    扩展访问的最基本类型是ExtensionAccessor,它提供了Extension的默认获取实现(由接口的default方法指定)

    1. public interface ExtensionAccessor {
    2. // ExtensionDirector继承自ExtensionAccessor, ExtensionAccessor反过来
    3. // 又从ExtensionDirector获取ExtensionLoader
    4. ExtensionDirector getExtensionDirector();
    5. default ExtensionLoader getExtensionLoader(Class type) {
    6. return this.getExtensionDirector().getExtensionLoader(type);
    7. }
    8. default T getExtension(Class type, String name) {
    9. ExtensionLoader extensionLoader = getExtensionLoader(type);
    10. return extensionLoader != null ? extensionLoader.getExtension(name) : null;
    11. }
    12. default T getAdaptiveExtension(Class type) {
    13. ExtensionLoader extensionLoader = getExtensionLoader(type);
    14. return extensionLoader != null ? extensionLoader.getAdaptiveExtension() : null;
    15. }
    16. default T getDefaultExtension(Class type) {
    17. ExtensionLoader extensionLoader = getExtensionLoader(type);
    18. return extensionLoader != null ? extensionLoader.getDefaultExtension() : null;
    19. }
    20. }

    上面的ExtensionAccessor塞入ExtensionDirector的方式,应该是用了代理设计模式提供了默认的实现。ExtensionAccessor提供了接口的同时,也充当着Proxy的角色,default关键字使得这种方式得以实现。

    3.4、ExtensionDirector

    ExtensionAccessor会将请求交给子类ExtensionDirector去处理,ExtensionDirector是一个带有作用域的扩展访问器,这一点从它带有属性ScopeModel可以看出

    1. public ExtensionDirector(ExtensionDirector parent, ExtensionScope scope, ScopeModel scopeModel) {
    2. // 这里传入了父ExtensionDirector,类似java的双亲委派机制
    3. this.parent = parent;
    4. // 传递作用域ExtensionScope和ScopeModel
    5. this.scope = scope;
    6. this.scopeModel = scopeModel;
    7. }

    从ExtensionAccessor调用ExtensionDirector的逻辑可以看到,ExtensionDirector会将扩展交给内部的ExtensionLoader去处理

    1. public ExtensionLoader getExtensionLoader(Class type) {
    2. checkDestroyed();
    3. if (type == null) {
    4. throw new IllegalArgumentException("Extension type == null");
    5. }
    6. if (!type.isInterface()) {
    7. throw new IllegalArgumentException("Extension type (" + type + ") is not an interface!");
    8. }
    9. if (!withExtensionAnnotation(type)) {
    10. throw new IllegalArgumentException("Extension type (" + type +
    11. ") is not an extension, because it is NOT annotated with @" + SPI.class.getSimpleName() + "!");
    12. }
    13. // 1. find in local cache
    14. // 根据传递的类型从本地缓存中获取
    15. ExtensionLoader loader = (ExtensionLoader) extensionLoadersMap.get(type);
    16. ExtensionScope scope = extensionScopeMap.get(type);
    17. // 如果扩展的作用域在本地缓存为空,则通过注解@SPI尝试去获取
    18. if (scope == null) {
    19. SPI annotation = type.getAnnotation(SPI.class);
    20. scope = annotation.scope();
    21. extensionScopeMap.put(type, scope);
    22. }
    23. // 对于第一次获取的类型,可能loader为空,如果作用域是仅限自我访问
    24. // 这时就需要创建一个针对该类型的extensionLoader
    25. if (loader == null && scope == ExtensionScope.SELF) {
    26. // create an instance in self scope
    27. loader = createExtensionLoader0(type);
    28. }
    29. // 2. find in parent
    30. // 这里用到了构造函数时传入进来的ExtensionDirector,如果本地找不到就去parent查找
    31. if (loader == null) {
    32. if (this.parent != null) {
    33. loader = this.parent.getExtensionLoader(type);
    34. }
    35. }
    36. // 3. create it
    37. // 创建针对该类的extensionLoader,注意这里是在上面获取parent之后
    38. // 所以正常是如果parent不为null的情况,这里是和java的双亲委派机制一样的
    39. // 有父ExtensionDirector去创建ExtensionLoader并且放在父ExtensionDirector的本地缓存中
    40. // 查找时先查找自己本地缓存,如果找不到再去父ExtensionDirector去查找
    41. if (loader == null) {
    42. loader = createExtensionLoader(type);
    43. }
    44. return loader;
    45. }

    ExtensionDirector获取ExtensionLoader的方式参考了Java的双亲委派机制,如果本地缓存中查找不到Class对应的ExtensionLoader,则是去父ExtensionDirector中查找。如果ExtensionDirector不为空,且Scope不是SELF,则由父ExtensionDirector去负责创建针对该扩展点类型的ExtensionLoader。

    这里也可以看出每一个扩展点对应一个ExtensionLoader。

    前面提到了ExtensionDirector是带有作用域ScopeModel的访问器,这点在创建ExtensionLoader中有所体现

    1. private ExtensionLoader createExtensionLoader(Class type) {
    2. ExtensionLoader loader = null;
    3. // 检查扩展点的ScopeModel是否和ExtensionDirector的ScopeMode是否一致
    4. if (isScopeMatched(type)) {
    5. // if scope is matched, just create it
    6. loader = createExtensionLoader0(type);
    7. }
    8. return loader;
    9. }
    10. private ExtensionLoader createExtensionLoader0(Class type) {
    11. checkDestroyed();
    12. ExtensionLoader loader;
    13. extensionLoadersMap.putIfAbsent(type, new ExtensionLoader(type, this, scopeModel));
    14. loader = (ExtensionLoader) extensionLoadersMap.get(type);
    15. return loader;
    16. }
    17. private boolean isScopeMatched(Class type) {
    18. // 通过注解@SPI获取当前扩展点的作用域
    19. final SPI defaultAnnotation = type.getAnnotation(SPI.class);
    20. return defaultAnnotation.scope().equals(scope);
    21. }

    上面逻辑的意思是,只有同个作用域的扩展点,才能被ExtensionDirector访问并且创建。但是在getExtensionLoader的时候可以看到,对于本地缓存没有的ExtensionLoader,是可以去父类中查找并返回的,也就是说父ExtensionDirector可以和子ExtensionDirector存在不一样的Scope,甚至比子ExtensionDirector更高的作用域。

    3.5、ExtensionLoader

    类似ClassLoader的作用,整个扩展机制的主要逻辑部分,其提供了配置的加载、缓存扩展类以及对象生成的工作。

    ExtensionLoader的主要入口是通过三个方法调用,分别是getExtension,getAdaptiveExtensionClass以及getActivateExtension三个方法。

    3.5.1、getExtension

    要记住一点是ExtensionLoader的每个实例只用于一个type,所以在初始化的时候会指定当前ExtensionLoader所能处理的type。

    1. ExtensionLoader(Class type, ExtensionDirector extensionDirector, ScopeModel scopeModel) {
    2. // 每一个ExtensionLoader对应一个type
    3. this.type = type;
    4. ...

    getExtension是最常用的方法,一般是通过指定name获取文件中对应的实现(name=com.xxx)。

    1. public T getExtension(String name) {
    2. T extension = getExtension(name, true);
    3. if (extension == null) {
    4. throw new IllegalArgumentException("Not find extension: " + name);
    5. }
    6. return extension;
    7. }
    8. // wrap表示是否要返回一个包装类
    9. public T getExtension(String name, boolean wrap) {
    10. checkDestroyed();
    11. if (StringUtils.isEmpty(name)) {
    12. throw new IllegalArgumentException("Extension name == null");
    13. }
    14. // 如果传递的name为true,则返回默认的扩展点实现
    15. if ("true".equals(name)) {
    16. return getDefaultExtension();
    17. }
    18. String cacheKey = name;
    19. if (!wrap) {
    20. cacheKey += "_origin";
    21. }
    22. // ExtensionLoader也会缓存类型的具体实现,类似Spring那样的bean单例模式
    23. final Holder holder = getOrCreateHolder(cacheKey);
    24. Object instance = holder.get();
    25. if (instance == null) {
    26. // 这里用Holder,而不是直接用具体扩展点实现的对象的原因是为了避免这里的锁冲突
    27. // 一个具体的扩展点实现对应一个Holder,这样不同的实现类在创建的时候,由于
    28. // holder的不同,synchronized就不是锁同一个对象,这样并发的时候减少锁冲突的作用
    29. // 这里也还常见的volatile、双重检查创建单例模式的写法
    30. // 我想想这里为啥用holder,其实holder就是给name对应类型的一个锁,每个name各自有一个
    31. // 如果不这么做的话,就必须得有外部一个全局的对象去避免创建对象的线程安全问题
    32. // 这样的话会造成并发创建慢
    33. synchronized (holder) {
    34. instance = holder.get();
    35. if (instance == null) {
    36. instance = createExtension(name, wrap);
    37. holder.set(instance);
    38. }
    39. }
    40. }
    41. return (T) instance;
    42. }
    43. 这里用了双判断法+Holder的方式创建实例,synchronized锁住的是给当前类型的Holder对象。这样做可以避免锁冲突。

      Dubbo肯定是懒加载的机制,不会一口气把所有的扩展点实现都实例化,只有用到的时候再去创建实例(当时类还是会加载的)。这里createExtension可以根据具体的name找到并实例化extension。

      1. private T createExtension(String name, boolean wrap) {
      2. Class clazz = getExtensionClasses().get(name);
      3. if (clazz == null || unacceptableExceptions.contains(name)) {
      4. throw findException(name);
      5. }
      6. try {
      7. // extensionInstances是缓存的对应类型的实例化对象,这里应该是每个类型一个对象的单例模式
      8. T instance = (T) extensionInstances.get(clazz);
      9. if (instance == null) {
      10. // createExtensionInstance负责初始化对象
      11. extensionInstances.putIfAbsent(clazz, createExtensionInstance(clazz));
      12. instance = (T) extensionInstances.get(clazz);、
      13. // 这里的postBefore和postAfter应该是类似实例前后的埋点操作
      14. instance = postProcessBeforeInitialization(instance, name);
      15. // 这里是注入实例的依赖,下文会介绍
      16. injectExtension(instance);
      17. instance = postProcessAfterInitialization(instance, name);
      18. }
      19. // wrap是是否包装的意思,类似AOP
      20. if (wrap) {
      21. List> wrapperClassesList = new ArrayList<>();
      22. if (cachedWrapperClasses != null) {
      23. wrapperClassesList.addAll(cachedWrapperClasses);
      24. wrapperClassesList.sort(WrapperComparator.COMPARATOR);
      25. Collections.reverse(wrapperClassesList);
      26. }
      27. if (CollectionUtils.isNotEmpty(wrapperClassesList)) {
      28. for (Class wrapperClass : wrapperClassesList) {
      29. Wrapper wrapper = wrapperClass.getAnnotation(Wrapper.class);
      30. boolean match = (wrapper == null) || ((ArrayUtils.isEmpty(
      31. wrapper.matches()) || ArrayUtils.contains(wrapper.matches(),
      32. name)) && !ArrayUtils.contains(wrapper.mismatches(), name));
      33. if (match) {
      34. // 将新生成的实例注入到wrapper中,不过Wrapper类必须构造函数要有可以加入代理的属性
      35. instance = injectExtension(
      36. (T) wrapperClass.getConstructor(type).newInstance(instance));
      37. instance = postProcessAfterInitialization(instance, name);
      38. }
      39. }
      40. }
      41. }
      42. // Warning: After an instance of Lifecycle is wrapped by cachedWrapperClasses, it may not still be Lifecycle instance, this application may not invoke the lifecycle.initialize hook.
      43. initExtension(instance);
      44. return instance;
      45. } catch (Throwable t) {
      46. throw new IllegalStateException(
      47. "Extension instance (name: " + name + ", class: " + type + ") couldn't be instantiated: " + t.getMessage(),
      48. t);
      49. }
      50. }

      第一次实例化的时候,扩展点实现的信息全部为空,这时需要第一次扫描下文件的内容以及缓存到内存中,其中第一步就是获取文件内的扩展点实现的全路径。

      1. private Map> getExtensionClasses() {
      2. // cachedClasses指缓存文件中的扩展点实现已经对应的名字name
      3. Map> classes = cachedClasses.get();
      4. if (classes == null) {
      5. synchronized (cachedClasses) {
      6. // 再次获取避免等锁的时候有其他线程获取了
      7. classes = cachedClasses.get();
      8. if (classes == null) {
      9. try {
      10. // 第一次获取时为空,所以遍历文件查询
      11. classes = loadExtensionClasses();
      12. } catch (InterruptedException e) {
      13. logger.error(COMMON_ERROR_LOAD_EXTENSION, "", "",
      14. "Exception occurred when loading extension class (interface: " + type + ")",
      15. e);
      16. throw new IllegalStateException(
      17. "Exception occurred when loading extension class (interface: " + type + ")",
      18. e);
      19. }
      20. cachedClasses.set(classes);
      21. }
      22. }
      23. }
      24. return classes;
      25. }
      26. private Map> loadExtensionClasses() throws InterruptedException {
      27. checkDestroyed();
      28. // 缓存默认的扩展点实现,这里@SPI注解可以指定
      29. cacheDefaultExtensionName();
      30. Map> extensionClasses = new HashMap<>();
      31. // 分别通过三个不同优先级的扩展点实现获取地方加载
      32. for (LoadingStrategy strategy : strategies) {
      33. loadDirectory(extensionClasses, strategy, type.getName());
      34. // compatible with old ExtensionFactory
      35. if (this.type == ExtensionInjector.class) {
      36. loadDirectory(extensionClasses, strategy, ExtensionFactory.class.getName());
      37. }
      38. }
      39. return extensionClasses;
      40. }
      41. private void cacheDefaultExtensionName() {
      42. // 用于获取接口中的@SPI注解
      43. final SPI defaultAnnotation = type.getAnnotation(SPI.class);
      44. if (defaultAnnotation == null) {
      45. return;
      46. }
      47. // 这里的value是获取@SPI的value值,表示默认扩展点名
      48. String value = defaultAnnotation.value();
      49. if ((value = value.trim()).length() > 0) {
      50. // 默认的扩展点实现不能有多个
      51. String[] names = NAME_SEPARATOR.split(value);
      52. if (names.length > 1) {
      53. throw new IllegalStateException(
      54. "More than 1 default extension name on extension " + type.getName() + ": " + Arrays.toString(
      55. names));
      56. }
      57. if (names.length == 1) {
      58. cachedDefaultName = names[0];
      59. }
      60. }
      61. }

      Dubbo有三个不同优先级的扩展点实现的加载机制,也就是去哪些目录扫描扩展点实现的地方,通过LoadingStrategy表示。按优先级大小排序的话分别是

      DubboInternalLoadingStrategy(META-INF/dubbo/internal/) > DubboLoadingStrategy(META-INF/dubbo/) > ServicesLoadingStrategy(META-INF/services/)
      1. private void loadDirectory(Map> extensionClasses, LoadingStrategy strategy,
      2. String type) throws InterruptedException {
      3. loadDirectoryInternal(extensionClasses, strategy, type);
      4. try {
      5. String oldType = type.replace("org.apache", "com.alibaba");
      6. if (oldType.equals(type)) {
      7. return;
      8. }
      9. //if class not found,skip try to load resources
      10. ClassUtils.forName(oldType);
      11. loadDirectoryInternal(extensionClasses, strategy, oldType);
      12. } catch (ClassNotFoundException classNotFoundException) {
      13. }
      14. }
      15. private void loadDirectoryInternal(Map> extensionClasses,
      16. LoadingStrategy loadingStrategy, String type)
      17. throws InterruptedException {
      18. // 文件名通常是扩展点接口的全路径,这里不同的策略会有不同的文件夹目录,所以加起来就是全路径
      19. String fileName = loadingStrategy.directory() + type;
      20. try {
      21. List classLoadersToLoad = new LinkedList<>();
      22. // try to load from ExtensionLoader's ClassLoader first
      23. // 这里是指是否loadingStrategy的classLoader要和ExtensionLoader的一样
      24. // 我暂时能想到的是这样加载效率会高一点,这样ExtensionLoader和扩展点对应的ClassLoader是同一个
      25. // findClass的时候就可以直接找到,我猜的
      26. if (loadingStrategy.preferExtensionClassLoader()) {
      27. ClassLoader extensionLoaderClassLoader = ExtensionLoader.class.getClassLoader();
      28. if (ClassLoader.getSystemClassLoader() != extensionLoaderClassLoader) {
      29. classLoadersToLoad.add(extensionLoaderClassLoader);
      30. }
      31. }
      32. if (specialSPILoadingStrategyMap.containsKey(type)) {
      33. String internalDirectoryType = specialSPILoadingStrategyMap.get(type);
      34. //skip to load spi when name don't match
      35. if (!LoadingStrategy.ALL.equals(
      36. internalDirectoryType) && !internalDirectoryType.equals(
      37. loadingStrategy.getName())) {
      38. return;
      39. }
      40. classLoadersToLoad.clear();
      41. classLoadersToLoad.add(ExtensionLoader.class.getClassLoader());
      42. } else {
      43. // load from scope model
      44. Set classLoaders = scopeModel.getClassLoaders();
      45. if (CollectionUtils.isEmpty(classLoaders)) {
      46. // 直接从类路径下获取这个文件,注意这里是systemResource,会调用systemClassLoader获取
      47. // 那这样看LoadStrategy只是指定了优先级和去哪里找的路径
      48. // 注意这里的ClassLoader是去所有的类路径下寻找fileName,可以能不同的包下会有相同名字的目录和文件名
      49. // 所以这里会返回多个
      50. Enumeration resources = ClassLoader.getSystemResources(fileName);
      51. if (resources != null) {
      52. while (resources.hasMoreElements()) {
      53. // 这里就是读取文件的每一行,然后分析=两边的name和实现的全路径,并且加载类到extensionClasses中
      54. loadResource(extensionClasses, null, resources.nextElement(),
      55. loadingStrategy.overridden(), loadingStrategy.includedPackages(),
      56. loadingStrategy.excludedPackages(),
      57. loadingStrategy.onlyExtensionClassLoaderPackages());
      58. }
      59. }
      60. } else {
      61. classLoadersToLoad.addAll(classLoaders);
      62. }
      63. }
      64. Map> resources = ClassLoaderResourceLoader.loadResources(
      65. fileName, classLoadersToLoad);
      66. resources.forEach(((classLoader, urls) -> {
      67. loadFromClass(extensionClasses, loadingStrategy.overridden(), urls, classLoader,
      68. loadingStrategy.includedPackages(), loadingStrategy.excludedPackages(),
      69. loadingStrategy.onlyExtensionClassLoaderPackages());
      70. }));
      71. } catch (InterruptedException e) {
      72. throw e;
      73. } catch (Throwable t) {
      74. logger.error(COMMON_ERROR_LOAD_EXTENSION, "", "",
      75. "Exception occurred when loading extension class (interface: " + type + ", description file: " + fileName + ").",
      76. t);
      77. }
      78. }

      上面这里如何去从文件中获取扩展点实现的逻辑还是比较简单的,根据内部设定的LoadStrategy去目录下的查找扩展点的接口全路径的文件,每一行读取获取name和扩展点实现的类全路径。这里获取的时候有检查是否带=的情况,估计是因为老版本的dubbo没有这个name或者是为了兼容java原生的SPI? 

      这里还有一个点就是扩展点实现的装配问题,首先需要知道有哪些依赖,这些依赖的类型是什么。Dubbo的方案是查找Java标准的setter方法。即方法名以set开始,只有一个参数。如果扩展类中有这样的set方法,Dubbo会对其进行依赖注入,类似于Spring的set方法注入。 但是Dubbo中的依赖注入比Spring要复杂,因为Spring注入的都是Spring bean,都是由Spring容器来管理的。而Dubbo的依赖注入中,需要注入的可能是另一个Dubbo的扩展,也可能是一个Spring Bean,或是Google guice的组件,或其他任何一个框架中的组件。Dubbo需要能够从任何一个场景中加载扩展。在injectExtension方法中。

      1. private T injectExtension(T instance) {
      2. if (injector == null) {
      3. return instance;
      4. }
      5. try {
      6. // 获取类中所有的方法
      7. for (Method method : instance.getClass().getMethods()) {
      8. // DUBBO通过判断方法是否为set方法判断是否是属性注入
      9. if (!isSetter(method)) {
      10. continue;
      11. }
      12. /**
      13. * Check {@link DisableInject} to see if we need auto-injection for this property
      14. */
      15. // DisableInject注解可以禁止自动注入
      16. if (method.isAnnotationPresent(DisableInject.class)) {
      17. continue;
      18. }
      19. // When spiXXX implements ScopeModelAware, ExtensionAccessorAware,
      20. // the setXXX of ScopeModelAware and ExtensionAccessorAware does not need to be injected
      21. if (method.getDeclaringClass() == ScopeModelAware.class) {
      22. continue;
      23. }
      24. if (instance instanceof ScopeModelAware || instance instanceof ExtensionAccessorAware) {
      25. if (ignoredInjectMethodsDesc.contains(ReflectUtils.getDesc(method))) {
      26. continue;
      27. }
      28. }
      29. // Set方法只有一个参数
      30. Class pt = method.getParameterTypes()[0];
      31. if (ReflectUtils.isPrimitives(pt)) {
      32. continue;
      33. }
      34. try {
      35. // 获取set方法的属性,就是方法名去掉set开头后的字符串
      36. String property = getSetterProperty(method);
      37. // 这里是从injector中获取到实例,目前Dubbo支持默认从三个地方根据类型获取实例
      38. Object object = injector.getInstance(pt, property);
      39. if (object != null) {
      40. method.invoke(instance, object);
      41. }
      42. } catch (Exception e) {
      43. logger.error(COMMON_ERROR_LOAD_EXTENSION, "", "",
      44. "Failed to inject via method " + method.getName() + " of interface " + type.getName() + ": " + e.getMessage(),
      45. e);
      46. }
      47. }
      48. } catch (Exception e) {
      49. logger.error(COMMON_ERROR_LOAD_EXTENSION, "", "", e.getMessage(), e);
      50. }
      51. return instance;
      52. }

      这里是从injector中获取到对应的属性,注意injector本身也是一个扩展点,在初始化ExtensionLoader的时候创建

      1. this.injector = (type == ExtensionInjector.class ?null :
      2. extensionDirector.getExtensionLoader(ExtensionInjector.class).getAdaptiveExtension());

      目前Dubbo支持四种ExtensionInjector(老的版本是叫ExtensionFactory),分别是

      1. SpiExtensionInjector:Dubbo自己的Spi去加载Extension
      2. SpringExtensionInjector:从Spring容器中去加载Extension
      3. AdaptiveExtensionInjector: 自适应的AdaptiveExtensionLoader
      4. ScopeBeanExtensionInjector:从ScopeBeanFactory获取对应的属性

      这里getExtension的第二个参数是wrapper,表示是否返回一个包装类。那什么是wrapper类呢,Wrapper类是一个有复制构造函数的类,也是典型的装饰者模式。下面就是一个Wrapper类:

      1. class A{
      2. private A a;
      3. public A(A a){
      4. this.a = a;
      5. }
      6. }

      类A有一个构造函数public A(A a),构造函数的参数是A本身。这样的类就可以成为Dubbo扩展机制中的一个Wrapper类。

      在Dubbo中Wrapper类也是一个扩展点,和其他的扩展点一样,也是在META-INF文件夹中配置的。例如ProtocolFilterWrapper和ProtocolListenerWrapper就是在路径dubbo-rpc/dubbo-rpc-api/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.Protocol中配置的:

      1. filter=org.apache.dubbo.rpc.protocol.ProtocolFilterWrapper
      2. listener=org.apache.dubbo.rpc.protocol.ProtocolListenerWrapper
      3. mock=org.apache.dubbo.rpc.support.MockProtocol

      在Dubbo加载扩展配置文件时,也就是前面loadClass的方法中,如果检测到扩展点实现代用@Wrapper注解的话,就会把这个扩展点实现缓存起来

      1. private void loadClass(ClassLoader classLoader, Map> extensionClasses,
      2. java.net.URL resourceURL, Class clazz, String name,
      3. boolean overridden) {
      4. if (clazz.isAnnotationPresent(Adaptive.class)) {
      5. cacheAdaptiveClass(clazz, overridden);
      6. } else if (isWrapperClass(clazz)) {
      7. cacheWrapperClass(clazz);
      8. ...
      9. }
      10. private void cacheWrapperClass(Class clazz) {
      11. if (cachedWrapperClasses == null) {
      12. cachedWrapperClasses = new ConcurrentHashSet<>();
      13. }
      14. cachedWrapperClasses.add(clazz);
      15. }

      所以当需要时,ExtensionLoader会将Wrapper类返回而不是直接返回一个原生扩展点的实例。在需要强调的是,Wrapper也是需要和扩展点实现一起放入到文件中,以name=com.xxx.xxxWrapper的形式,ExtensionLoader获取到所有的Wrapper类之后进行缓存,在创建对象的时候会依次进行包装,注意这里因为都是继承了同一个接口,所以是可以依次包装。这但在createExtension也可以发现

      1. private T createExtension(String name, boolean wrap) {
      2. ...
      3. // wrap是是否包装的意思,类似AOP
      4. if (wrap) {
      5. List> wrapperClassesList = new ArrayList<>();
      6. if (cachedWrapperClasses != null) {
      7. wrapperClassesList.addAll(cachedWrapperClasses);
      8. // 这里对Wrapper类进行排序,可以自定义规则
      9. wrapperClassesList.sort(WrapperComparator.COMPARATOR);
      10. Collections.reverse(wrapperClassesList);
      11. }
      12. if (CollectionUtils.isNotEmpty(wrapperClassesList)) {
      13. // 遍历所有的Wrapper类,并且依次将返回的对象塞入
      14. for (Class wrapperClass : wrapperClassesList) {
      15. Wrapper wrapper = wrapperClass.getAnnotation(Wrapper.class);
      16. boolean match = (wrapper == null) || ((ArrayUtils.isEmpty(
      17. wrapper.matches()) || ArrayUtils.contains(wrapper.matches(),
      18. name)) && !ArrayUtils.contains(wrapper.mismatches(), name));
      19. if (match) {
      20. // 将新生成的实例注入到wrapper中,不过Wrapper类必须构造函数要有可以加入代理的属性
      21. instance = injectExtension(
      22. (T) wrapperClass.getConstructor(type).newInstance(instance));
      23. instance = postProcessAfterInitialization(instance, name);
      24. }
      25. }
      26. }
      27. }
      28. }

      这里也贴了Dubbo官方介绍的可扩展机制源码分析

      Dubbo可扩展机制源码解析icon-default.png?t=N7T8https://cn.dubbo.apache.org/zh-cn/blog/2019/05/02/dubbo%E5%8F%AF%E6%89%A9%E5%B1%95%E6%9C%BA%E5%88%B6%E6%BA%90%E7%A0%81%E8%A7%A3%E6%9E%90/

      3.5.2、getAdaptiveExtension

      官方是这样介绍自适应获取的,在 Dubbo 中,很多拓展都是通过 SPI 机制进行加载的,比如 Protocol、Cluster、LoadBalance 等。有时,有些拓展并不想在框架启动阶段被加载,而是希望在拓展方法被调用时,根据运行时参数进行加载。

      我个人对这段的解释是:Dubbo是基于URL总线的模式,所有的配置和连接信息都可以从URL这个类中获取。所有扩展点参数都作为了URL参数,URL 作为上下文信息贯穿整个扩展点设计体系。那么这里的自适应扩展就是根据传递的参数去创建对象,有点类似工厂模式的意思。那上面的getExtension不能做到吗?

      其实getExtension也是可以做到类似的效果,就是根据URL的参数去运行时初始化。只不过自适应扩展有更进一步的优化,自适应扩展可以动态生成关于只包含某个方法的实现。也就是扩展点(用@SPI标记的),可以在方法级别使用@Adaptive,这样程序运行时就会自动生成这个方法内容的实现,接口的其他实现会抛出异常。这个就是自适应扩展的优势。

      具体的逻辑实现这里就不介绍了,官方那里+上面的分析写了很多,具体可以跳转到官方bolg看下介绍。

      SPI自适应扩展icon-default.png?t=N7T8https://cn.dubbo.apache.org/zh-cn/docsv2.7/dev/source/adaptive-extension/

      3.5.3、getActivateExtension

      自适应扩展的注解是@Adaptive,而这里的激活扩展点则是@Activate。主要使用在有多个扩展点实现、需要同时根据不同条件被激活的场景中,如Filter需要多个同时激活,因为每个Filter实现的是不同的功能。

      举例来说:在工作中,某种时候存在这样的情形,需要同时启用某个接口的多个实现类,如Filter过滤器。我们希望某种条件下启用这一批实现,而另一种情况下启用那一批实现,比如:希望RPC调用的消费端和服务端,分别启用不同的两批Filter,这该怎么处理呢? —> 这时候dubbo的条件激活注解@Activate,就可以派上用场了。

      @Activate的参数有以下

      String[] group()URL中的分组如果匹配则激活
      String[] value()URL中如果包含该key值,则会激活
      String[] before()填写扩展点列表,表示哪些扩展点要在本扩展点之前激活
      String[] after()表示哪些扩展点需要在本扩展点之后激活
      int order()排序信息
      1. public List getActivateExtension(URL url, String[] values, String group) {
      2. checkDestroyed();
      3. // solve the bug of using @SPI's wrapper method to report a null pointer exception.
      4. Map, T> activateExtensionsMap = new TreeMap<>(activateComparator);
      5. // 这里的value是从URL中根据Key获取的值列表
      6. List names = values == null ? new ArrayList<>(0) : asList(values);
      7. Set namesSet = new HashSet<>(names);
      8. // 加锁的方式除了只加载一次之外,还有避免线程安全问题
      9. if (!namesSet.contains(REMOVE_VALUE_PREFIX + DEFAULT_KEY)) {
      10. if (cachedActivateGroups.size() == 0) {
      11. synchronized (cachedActivateGroups) {
      12. // cache all extensions
      13. if (cachedActivateGroups.size() == 0) {
      14. // 获取ExtensionLoader指定的type也就是扩展点的类,这部分可能出现在多个路径中
      15. // type是接口名
      16. getExtensionClasses();
      17. for (Map.Entry entry : cachedActivates.entrySet()) {
      18. // name是扩展点实现名, value是@Activate类的实现
      19. String name = entry.getKey();
      20. Object activate = entry.getValue();
      21. String[] activateGroup, activateValue;
      22. // @Activate中group和value都是激活的条件,其中group表示生产或者消费者
      23. // value则是自己定义的字符串数组,只有带有对应的字符串的Url才可以加载
      24. if (activate instanceof Activate) {
      25. activateGroup = ((Activate) activate).group();
      26. activateValue = ((Activate) activate).value();
      27. } else if (activate instanceof com.alibaba.dubbo.common.extension.Activate) {
      28. activateGroup = ((com.alibaba.dubbo.common.extension.Activate) activate).group();
      29. activateValue = ((com.alibaba.dubbo.common.extension.Activate) activate).value();
      30. } else {
      31. continue;
      32. }
      33. cachedActivateGroups.put(name,
      34. new HashSet<>(Arrays.asList(activateGroup)));
      35. String[][] keyPairs = new String[activateValue.length][];
      36. for (int i = 0; i < activateValue.length; i++) {
      37. // @Activate中value可能包含键值对
      38. if (activateValue[i].contains(":")) {
      39. keyPairs[i] = new String[2];
      40. String[] arr = activateValue[i].split(":");
      41. keyPairs[i][0] = arr[0];
      42. keyPairs[i][1] = arr[1];
      43. } else {
      44. keyPairs[i] = new String[1];
      45. keyPairs[i][0] = activateValue[i];
      46. }
      47. }
      48. cachedActivateValues.put(name, keyPairs);
      49. }
      50. }
      51. }
      52. }
      53. // @Activate的一个例子:
      54. // @Activate(group = CommonConstants.CONSUMER, value = Constants.SERVICE_AUTH)
      55. // 当URL的key带有Constants.SERVICE_AUTH,该扩展点实现就可以被激活
      56. //
      57. // traverse all cached extensions
      58. cachedActivateGroups.forEach((name, activateGroup) -> {
      59. if (isMatchGroup(group, activateGroup) && !namesSet.contains(
      60. name) && !namesSet.contains(REMOVE_VALUE_PREFIX + name) && isActive(
      61. cachedActivateValues.get(name), url)) {
      62. activateExtensionsMap.put(getExtensionClass(name), getExtension(name));
      63. }
      64. });
      65. }
      66. // namesSet是URL的Key的值列表
      67. // 扩展点实现的文件中,DEFAULT_KEY也就是有default=com.xxx的
      68. if (namesSet.contains(DEFAULT_KEY)) {
      69. // will affect order
      70. // `ext1,default,ext2` means ext1 will happens before all of the default extensions while ext2 will after them
      71. ArrayList extensionsResult = new ArrayList<>(
      72. activateExtensionsMap.size() + names.size());
      73. for (String name : names) {
      74. if (name.startsWith(REMOVE_VALUE_PREFIX) || namesSet.contains(
      75. REMOVE_VALUE_PREFIX + name)) {
      76. continue;
      77. }
      78. if (DEFAULT_KEY.equals(name)) {
      79. extensionsResult.addAll(activateExtensionsMap.values());
      80. continue;
      81. }
      82. // 获取扩展点实现的时候,会有name=具体类路径的方式
      83. // 这里就是检查方法进入时的参数URL带有的key对应的value是否有指定这个name
      84. // 有的话就选择扩展点实现
      85. if (containsExtension(name)) {
      86. extensionsResult.add(getExtension(name));
      87. }
      88. }
      89. return extensionsResult;
      90. } else {
      91. // add extensions, will be sorted by its order
      92. for (String name : names) {
      93. if (name.startsWith(REMOVE_VALUE_PREFIX) || namesSet.contains(
      94. REMOVE_VALUE_PREFIX + name)) {
      95. continue;
      96. }
      97. if (DEFAULT_KEY.equals(name)) {
      98. continue;
      99. }
      100. // 当这里的Key指定具体的名字时,而名字对应扩展点实现时初始化?
      101. if (containsExtension(name)) {
      102. activateExtensionsMap.put(getExtensionClass(name), getExtension(name));
      103. }
      104. }
      105. return new ArrayList<>(activateExtensionsMap.values());
      106. }
      107. }

      Dubbo的SPI机制先介绍到这,改天有时间再优化下这篇文章,把代码介绍部分分析好点>_< 

    44. 相关阅读:
      Linux基本指令一
      Bean 作用域和生命周期
      c语言分层理解(c语言字符串+内存库函数)
      实战指南:使用 xUnit 和 ASP.NET Core 进行集成测试【完整教程】
      windows 使用 pybind11
      操作系统基础教程——第五章课后作业答案
      【LeetCode刷题-字符串】--6.N字形变换
      【Gradle】三、深入了解Gradle
      【C++入门篇】深入理解函数重载
      Puppeteer国产镜像配置
    45. 原文地址:https://blog.csdn.net/NerverSimply/article/details/132640146