其实我们在SPI源码阅读的时候,已经阅读过Dubbo中的IOC/APO源码部分了,接下来我们再详细的跟踪一下复习一遍。

IOC

  1. **ServiceConfig.java**
  1. public synchronized void export() {
  2. // 检测所有的注册中心可用性,并进一步完善<dubbo:service/>的配置
  3. checkAndUpdateSubConfigs();
  4. // 若设置的export为false,则不进行服务暴露,直接结束
  5. if (!shouldExport()) {
  6. return;
  7. }
  8. // 若设置了delay属性,则进行延迟暴露
  9. if (shouldDelay()) {
  10. DELAY_EXPORT_EXECUTOR.schedule(this::doExport, getDelay(), TimeUnit.MILLISECONDS);
  11. } else {
  12. doExport();
  13. }
  14. }
  15. public void checkAndUpdateSubConfigs() {
  16. // 如果用户没有自定义配置,则使用默认的配置信息
  17. completeCompoundConfigs();
  18. // Config Center should always being started first.
  19. startConfigCenter();
  20. checkDefault();
  21. checkProtocol();
  22. checkApplication();
  23. // if protocol is not injvm checkRegistry
  24. // 若不是本地服务暴露,则检测所有注册中心的可用性
  25. if (!isOnlyInJvm()) {
  26. checkRegistry();
  27. }
  28. this.refresh();
  29. checkMetadataReport();
  30. if (StringUtils.isEmpty(interfaceName)) {
  31. throw new IllegalStateException("<dubbo:service interface=\"\" /> interface not allow null!");
  32. }
  33. if (ref instanceof GenericService) {
  34. interfaceClass = GenericService.class;
  35. if (StringUtils.isEmpty(generic)) {
  36. generic = Boolean.TRUE.toString();
  37. }
  38. } else {
  39. try {
  40. interfaceClass = Class.forName(interfaceName, true, Thread.currentThread()
  41. .getContextClassLoader());
  42. } catch (ClassNotFoundException e) {
  43. throw new IllegalStateException(e.getMessage(), e);
  44. }
  45. checkInterfaceAndMethods(interfaceClass, methods);
  46. checkRef();
  47. generic = Boolean.FALSE.toString();
  48. }
  49. if (local != null) {
  50. if ("true".equals(local)) {
  51. local = interfaceName + "Local";
  52. }
  53. Class<?> localClass;
  54. try {
  55. localClass = ClassUtils.forNameWithThreadContextClassLoader(local);
  56. } catch (ClassNotFoundException e) {
  57. throw new IllegalStateException(e.getMessage(), e);
  58. }
  59. if (!interfaceClass.isAssignableFrom(localClass)) {
  60. throw new IllegalStateException("The local implementation class " + localClass.getName() + " not implement interface " + interfaceName);
  61. }
  62. }
  63. if (stub != null) {
  64. if ("true".equals(stub)) {
  65. stub = interfaceName + "Stub";
  66. }
  67. Class<?> stubClass;
  68. try {
  69. stubClass = ClassUtils.forNameWithThreadContextClassLoader(stub);
  70. } catch (ClassNotFoundException e) {
  71. throw new IllegalStateException(e.getMessage(), e);
  72. }
  73. if (!interfaceClass.isAssignableFrom(stubClass)) {
  74. throw new IllegalStateException("The stub implementation class " + stubClass.getName() + " not implement interface " + interfaceName);
  75. }
  76. }
  77. checkStubAndLocal(interfaceClass);
  78. checkMock(interfaceClass);
  79. }

AbstractInterfaceConfig.java

  1. protected void checkRegistry() {
  2. loadRegistriesFromBackwardConfig();
  3. convertRegistryIdsToRegistries();
  4. // 遍历所有注册中心,只要有一个不可用,则直接抛出异常
  5. for (RegistryConfig registryConfig : registries) {
  6. if (!registryConfig.isValid()) {
  7. throw new IllegalStateException("No registry config found or it's not a valid config! " +
  8. "The registry config is: " + registryConfig);
  9. }
  10. }
  11. // 使用注册中心作为配置中心,如果有必要的话(没有定义配置中心)
  12. useRegistryForConfigIfNecessary();
  13. }
  14. private void useRegistryForConfigIfNecessary() {
  15. registries.stream().filter(RegistryConfig::isZookeeperProtocol).findFirst().ifPresent(rc -> {
  16. // we use the loading status of DynamicConfiguration to decide whether ConfigCenter has been initiated.
  17. Environment.getInstance().getDynamicConfiguration().orElseGet(() -> {
  18. ConfigManager configManager = ConfigManager.getInstance();
  19. ConfigCenterConfig cc = configManager.getConfigCenter().orElse(new ConfigCenterConfig());
  20. // 使用注册中心初始化配置中心
  21. cc.setProtocol(rc.getProtocol());
  22. cc.setAddress(rc.getAddress());
  23. cc.setHighestPriority(false);
  24. setConfigCenter(cc);
  25. // 开启配置中心
  26. startConfigCenter();
  27. return null;
  28. });
  29. });
  30. }
  31. void startConfigCenter() {
  32. if (configCenter == null) {
  33. ConfigManager.getInstance().getConfigCenter().ifPresent(cc -> this.configCenter = cc);
  34. }
  35. if (this.configCenter != null) {
  36. // TODO there may have duplicate refresh
  37. this.configCenter.refresh();
  38. // 从配置中心读取动态配置数据,准备运行环境
  39. prepareEnvironment();
  40. }
  41. ConfigManager.getInstance().refreshAll();
  42. }
  43. private void prepareEnvironment() {
  44. if (configCenter.isValid()) {
  45. if (!configCenter.checkOrUpdateInited()) {
  46. return;
  47. }
  48. // 获取动态配置
  49. DynamicConfiguration dynamicConfiguration = getDynamicConfiguration(configCenter.toUrl());
  50. String configContent = dynamicConfiguration.getProperties(configCenter.getConfigFile(), configCenter.getGroup());
  51. String appGroup = application != null ? application.getName() : null;
  52. String appConfigContent = null;
  53. if (StringUtils.isNotEmpty(appGroup)) {
  54. appConfigContent = dynamicConfiguration.getProperties
  55. (StringUtils.isNotEmpty(configCenter.getAppConfigFile()) ? configCenter.getAppConfigFile() : configCenter.getConfigFile(),
  56. appGroup
  57. );
  58. }
  59. try {
  60. Environment.getInstance().setConfigCenterFirst(configCenter.isHighestPriority());
  61. Environment.getInstance().updateExternalConfigurationMap(parseProperties(configContent));
  62. Environment.getInstance().updateAppExternalConfigurationMap(parseProperties(appConfigContent));
  63. } catch (IOException e) {
  64. throw new IllegalStateException("Failed to parse configurations from Config Center.", e);
  65. }
  66. }
  67. }
  68. private DynamicConfiguration getDynamicConfiguration(URL url) {
  69. // 获取动态配置工厂DynamicConfigurationFactory的名称为zookeeper的扩展类实例
  70. DynamicConfigurationFactory factories = ExtensionLoader
  71. .getExtensionLoader(DynamicConfigurationFactory.class)
  72. .getExtension(url.getProtocol()); //
  73. DynamicConfiguration configuration = factories.getDynamicConfiguration(url);
  74. Environment.getInstance().setDynamicConfiguration(configuration);
  75. return configuration;
  76. }

ExtensionLoader.java

  1. // 获取指定名称的扩展类实例
  2. @SuppressWarnings("unchecked")
  3. public T getExtension(String name) {
  4. if (StringUtils.isEmpty(name)) {
  5. throw new IllegalArgumentException("Extension name == null");
  6. }
  7. if ("true".equals(name)) {
  8. return getDefaultExtension();
  9. }
  10. final Holder<Object> holder = getOrCreateHolder(name);
  11. Object instance = holder.get();
  12. if (instance == null) {
  13. synchronized (holder) {
  14. instance = holder.get();
  15. if (instance == null) {
  16. // 创建指定名称的扩展类实例
  17. instance = createExtension(name);
  18. holder.set(instance);
  19. }
  20. }
  21. }
  22. return (T) instance;
  23. }
  24. private T createExtension(String name) {
  25. // getExtensionClasses() 返回当前SPI接口的所有直接扩展类,是个map
  26. // 其key为扩展名,value为直接扩展类的class
  27. Class<?> clazz = getExtensionClasses().get(name);
  28. if (clazz == null) {
  29. throw findException(name);
  30. }
  31. try {
  32. // 从缓存中获取指定类对应的实例,若为null,则创建一个实例
  33. T instance = (T) EXTENSION_INSTANCES.get(clazz);
  34. if (instance == null) {
  35. EXTENSION_INSTANCES.putIfAbsent(clazz, clazz.newInstance());
  36. instance = (T) EXTENSION_INSTANCES.get(clazz);
  37. }
  38. // 调用instance实例的setter完成注入
  39. injectExtension(instance);
  40. // 获取当前SPI接口类型的所有wrapper类
  41. Set<Class<?>> wrapperClasses = cachedWrapperClasses;
  42. // 遍历所有wrapper,逐层对instance实例进行包装
  43. if (CollectionUtils.isNotEmpty(wrapperClasses)) {
  44. for (Class<?> wrapperClass : wrapperClasses) {
  45. instance = injectExtension((T) wrapperClass.getConstructor(type).newInstance(instance));
  46. }
  47. }
  48. // 返回的是包装过的instance
  49. return instance;
  50. } catch (Throwable t) {
  51. throw new IllegalStateException("Extension instance (name: " + name + ", class: " +
  52. type + ") couldn't be instantiated: " + t.getMessage(), t);
  53. }
  54. }
  55. private T injectExtension(T instance) {
  56. try {
  57. if (objectFactory != null) {
  58. // 遍历当前instance中的所有方法
  59. for (Method method : instance.getClass().getMethods()) {
  60. // 仅对setter方法进行处理
  61. if (isSetter(method)) {
  62. /**
  63. * Check {@link DisableInject} to see if we need auto injection for this property
  64. */
  65. // 若一个setter方法上有@DisableInject注解,则不进行注入
  66. if (method.getAnnotation(DisableInject.class) != null) {
  67. continue;
  68. }
  69. // 获取当前setter方法的参数类型
  70. Class<?> pt = method.getParameterTypes()[0];
  71. // 若setter方法的参数类型为基本数据类型,则不进行注入
  72. if (ReflectUtils.isPrimitives(pt)) {
  73. continue;
  74. }
  75. try {
  76. // 获取setter方法的形参名称
  77. String property = getSetterProperty(method);
  78. // 获取要注入的实例,即setter的实参
  79. Object object = objectFactory.getExtension(pt, property);
  80. if (object != null) {
  81. // 调用setter完成注入
  82. method.invoke(instance, object);
  83. }
  84. } catch (Exception e) {
  85. logger.error("Failed to inject via method " + method.getName()
  86. + " of interface " + type.getName() + ": " + e.getMessage(), e);
  87. }
  88. }
  89. }
  90. }
  91. } catch (Exception e) {
  92. logger.error(e.getMessage(), e);
  93. }
  94. return instance;
  95. }

6.Dubbo中的IOC,APO源码阅读 - 图1

6.Dubbo中的IOC,APO源码阅读 - 图2

  1. public <T> T getExtension(Class<T> type, String name) {
  2. // 若当前type为SPI接口
  3. if (type.isInterface() && type.isAnnotationPresent(SPI.class)) {
  4. ExtensionLoader<T> loader = ExtensionLoader.getExtensionLoader(type);
  5. // 若当前type的直接扩展类不空,则返回其adaptive实例
  6. if (!loader.getSupportedExtensions().isEmpty()) {
  7. return loader.getAdaptiveExtension();
  8. }
  9. }
  10. return null;
  11. }

ExtensionLoader.java

  1. public <T> T getExtension(Class<T> type, String name) {
  2. // 若当前type为SPI接口
  3. if (type.isInterface() && type.isAnnotationPresent(SPI.class)) {
  4. ExtensionLoader<T> loader = ExtensionLoader.getExtensionLoader(type);
  5. // 若当前type的直接扩展类不空,则返回其adaptive实例
  6. if (!loader.getSupportedExtensions().isEmpty()) {
  7. return loader.getAdaptiveExtension();
  8. }
  9. }
  10. return null;
  11. }

6.Dubbo中的IOC,APO源码阅读 - 图3

  1. public <T> T getExtension(Class<T> type, String name) {
  2. //SPI should be get from SpiExtensionFactory
  3. // 若当前type为SPI接口,则直接结束,因为Spring方式不处理SPI接口实例的创建
  4. if (type.isInterface() && type.isAnnotationPresent(SPI.class)) {
  5. return null;
  6. }
  7. // 遍历所有Spring容器,根据名称从中查找实例
  8. for (ApplicationContext context : CONTEXTS) {
  9. if (context.containsBean(name)) {
  10. Object bean = context.getBean(name);
  11. if (type.isInstance(bean)) {
  12. return (T) bean;
  13. }
  14. }
  15. }
  16. logger.warn("No spring extension (bean) named:" + name + ", try to find an extension (bean) of type " + type.getName());
  17. // 这个type不能是Object
  18. if (Object.class == type) {
  19. return null;
  20. }
  21. // 遍历所有Spring容器,根据类型从中查找实例
  22. for (ApplicationContext context : CONTEXTS) {
  23. try {
  24. return context.getBean(type);
  25. } catch (NoUniqueBeanDefinitionException multiBeanExe) {
  26. logger.warn("Find more than 1 spring extensions (beans) of type " + type.getName() + ", will stop auto injection. Please make sure you have specified the concrete parameter type and there's only one extension of that type.");
  27. } catch (NoSuchBeanDefinitionException noBeanExe) {
  28. if (logger.isDebugEnabled()) {
  29. logger.debug("Error when get spring extension(bean) for type:" + type.getName(), noBeanExe);
  30. }
  31. }
  32. }
  33. logger.warn("No spring extension (bean) named:" + name + ", type:" + type.getName() + " found, stop get bean.");
  34. return null;
  35. }

AOP

  1. Dubbo 的 AOP 是对 SPI 扩展类进行增强的方式,而 Wrapper 机制就是对 SPI 扩展类的增强。不同 SPI 的不同 Wrapper,其增强的功能不同。这里引用一下我们之前在学习Dubbo中的四大扩展机制中的Wraper示例。它会生成一个Adaptive扩展类,它的格式是这样的。
  1. package <SPI 接口所在包>;
  2. public class SPI 接口名$Adpative implements SPI 接口 {
  3. public adaptiveMethod (arg0, arg1, ...) {
  4. // 注意,下面的判断仅对 URL 类型,或可以获取到 URL 类型值的参数进行判断
  5. // 例如,dubbo 的 Invoker 类型中就包含有 URL 属性
  6. if(arg1==null)
  7. throw new IllegalArgumentException(异常信息);
  8. if(arg1.getUrl()==null)
  9. throw new IllegalArgumentException(异常信息);
  10. URL url = arg1.getUrl();
  11. // 其会根据@Adaptive 注解上声明的 Key 的顺序,从 URL 获取 Value,
  12. // 作为实际扩展类。若有默认扩展类,则获取默认扩展类名;否则获取
  13. // 指定扩展名名。
  14. String extName = url.get 接口名() == null?默认扩展前辍名:url.get 接口名();
  15. if(extName==null) throw new IllegalStateException(异常信息);
  16. SPI 接口 extension = ExtensionLoader.getExtensionLoader(SPI 接口.class)
  17. .getExtension(extName);
  18. return extension. adaptiveMethod(arg0, arg1, ...);
  19. }
  20. public unAdaptiveMethod( arg0, arg1, ...) {
  21. throw new UnsupportedOperationException(异常信息);
  22. }
  23. }

它会调用getExtensionLoader()创建并执行这个类,然后再去调用被包装的真正的业务方法。从而达到AOP思想的增强。