标签解析

7.Dubbo标签解析及重要接口源码阅读 - 图1

dubbo的jar包依赖里面,可以看到两个文件:

spring.schemas

  1. http\://dubbo.apache.org/schema/dubbo/dubbo.xsd=META-INF/dubbo.xsd
  2. http\://code.alibabatech.com/schema/dubbo/dubbo.xsd=META-INF/compat/dubbo.xsd

spring.handlers

  1. http\://dubbo.apache.org/schema/dubbo=org.apache.dubbo.config.spring.schema.DubboNamespaceHandler <!--解析标签的类-->
  2. http\://code.alibabatech.com/schema/dubbo=org.apache.dubbo.config.spring.schema.DubboNamespaceHandler

DubboNamespaceHandler.java

  1. @Override
  2. public void init() {
  3. //这里是专门解析<dubbo:application />标签的, ApplicationConfig.class里面包含了标签里面所有的属性定义。下面的标签解析也是一样的意思
  4. registerBeanDefinitionParser("application", new DubboBeanDefinitionParser(ApplicationConfig.class, true));
  5. registerBeanDefinitionParser("module", new DubboBeanDefinitionParser(ModuleConfig.class, true));
  6. registerBeanDefinitionParser("registry", new DubboBeanDefinitionParser(RegistryConfig.class, true));
  7. registerBeanDefinitionParser("config-center", new DubboBeanDefinitionParser(ConfigCenterBean.class, true));
  8. registerBeanDefinitionParser("metadata-report", new DubboBeanDefinitionParser(MetadataReportConfig.class, true));
  9. registerBeanDefinitionParser("monitor", new DubboBeanDefinitionParser(MonitorConfig.class, true));
  10. registerBeanDefinitionParser("metrics", new DubboBeanDefinitionParser(MetricsConfig.class, true));
  11. registerBeanDefinitionParser("provider", new DubboBeanDefinitionParser(ProviderConfig.class, true));
  12. registerBeanDefinitionParser("consumer", new DubboBeanDefinitionParser(ConsumerConfig.class, true));
  13. registerBeanDefinitionParser("protocol", new DubboBeanDefinitionParser(ProtocolConfig.class, true));
  14. registerBeanDefinitionParser("service", new DubboBeanDefinitionParser(ServiceBean.class, true));
  15. registerBeanDefinitionParser("reference", new DubboBeanDefinitionParser(ReferenceBean.class, false));
  16. registerBeanDefinitionParser("annotation", new AnnotationBeanDefinitionParser());
  17. }

DubboBeanDefinitionParser.java

  1. /**
  2. * Dubbo标签解析器构造器
  3. * @param beanClass 标签属性读出值所封装的类型
  4. * @param required 指定id属性在当前标签中是否是必须的
  5. */
  6. public DubboBeanDefinitionParser(Class<?> beanClass, boolean required) {
  7. this.beanClass = beanClass;
  8. this.required = required;
  9. }
  10. /**
  11. * 解析指定标签
  12. * @param element 要解析的标签元素
  13. * @param parserContext 解析上下文,其中包含了当前配置文件中所有其它标签的解析信息
  14. * @param beanClass 标签属性读出值所封装的类型,是一种物理性封装
  15. * @param required 指定id属性在当前标签中是否是必须的
  16. * @return 解析对象。即当前标签最终解析出的“逻辑实例”的Bean定义器实例
  17. */
  18. @SuppressWarnings("unchecked")
  19. private static BeanDefinition parse(Element element, ParserContext parserContext, Class<?> beanClass, boolean required) {
  20. // ========================== 1 创建并初始化解析对象 ================
  21. RootBeanDefinition beanDefinition = new RootBeanDefinition();
  22. beanDefinition.setBeanClass(beanClass);
  23. beanDefinition.setLazyInit(false);//是否开启懒加载机制
  24. // ========================== 2 解决id问题:为空的问题 与 重复的问题 ================
  25. // 获取当前标签中的id属性
  26. String id = element.getAttribute("id");
  27. if (StringUtils.isEmpty(id) && required) {
  28. // 获取当前标签的name属性
  29. String generatedBeanName = element.getAttribute("name");
  30. if (StringUtils.isEmpty(generatedBeanName)) {
  31. // 若当前解析的标签为<dubbo:protocol/>,则name属性值设置为dubbo
  32. // 否则,取interface属性值
  33. if (ProtocolConfig.class.equals(beanClass)) {
  34. generatedBeanName = "dubbo";
  35. } else {
  36. generatedBeanName = element.getAttribute("interface");
  37. }
  38. }
  39. // 若到这里name属性仍为空,则name属性值取beanClass的类名
  40. if (StringUtils.isEmpty(generatedBeanName)) {
  41. generatedBeanName = beanClass.getName();
  42. }
  43. // 代码走到这里,name属性一定不空,即id属性一定不空
  44. id = generatedBeanName;
  45. int counter = 2;
  46. // 遍历解析对象上下文,判断生成的id是否发生重复。
  47. // 若重复,则在其名称后添加一个数字,走到不重复为止
  48. while (parserContext.getRegistry().containsBeanDefinition(id)) {
  49. id = generatedBeanName + (counter++);
  50. }
  51. } // end-if
  52. // ========================== 3 将id属性写入到解析对象 ================
  53. if (id != null && id.length() > 0) {
  54. // 若用户在标签中自己指定的id属性在解析上下文中重复,则直接抛出异常
  55. if (parserContext.getRegistry().containsBeanDefinition(id)) {
  56. throw new IllegalStateException("Duplicate spring bean id " + id);
  57. }
  58. // 将 id-解析对象 写入到解析上下文
  59. parserContext.getRegistry().registerBeanDefinition(id, beanDefinition);
  60. // 将id属性写入到解析对象中
  61. beanDefinition.getPropertyValues().addPropertyValue("id", id);
  62. }
  63. // ========================== 4 对特殊标签的特殊处理 ================
  64. // 处理<dubbo:protocol/>标签
  65. if (ProtocolConfig.class.equals(beanClass)) {
  66. for (String name : parserContext.getRegistry().getBeanDefinitionNames()) {
  67. BeanDefinition definition = parserContext.getRegistry().getBeanDefinition(name);
  68. PropertyValue property = definition.getPropertyValues().getPropertyValue("protocol");
  69. if (property != null) {
  70. Object value = property.getValue();
  71. if (value instanceof ProtocolConfig && id.equals(((ProtocolConfig) value).getName())) {
  72. definition.getPropertyValues().addPropertyValue("protocol", new RuntimeBeanReference(id));
  73. }
  74. }
  75. }
  76. // 处理<dubbo:service/>标签
  77. } else if (ServiceBean.class.equals(beanClass)) {
  78. String className = element.getAttribute("class");
  79. if (className != null && className.length() > 0) {
  80. RootBeanDefinition classDefinition = new RootBeanDefinition();
  81. classDefinition.setBeanClass(ReflectUtils.forName(className));
  82. classDefinition.setLazyInit(false);
  83. parseProperties(element.getChildNodes(), classDefinition);
  84. beanDefinition.getPropertyValues().addPropertyValue("ref", new BeanDefinitionHolder(classDefinition, id + "Impl"));
  85. }
  86. // 处理<dubbo:provider/>标签
  87. } else if (ProviderConfig.class.equals(beanClass)) {
  88. // 嵌套解析<dubbo:servie/>与<dubbo:provider/>标签
  89. parseNested(element, parserContext, ServiceBean.class, true, "service", "provider", id, beanDefinition);
  90. // 处理<dubbo:consumer/>标签
  91. } else if (ConsumerConfig.class.equals(beanClass)) {
  92. // 嵌套解析<dubbo:reference/>与<dubbo:consumer/>标签
  93. parseNested(element, parserContext, ReferenceBean.class, false, "reference", "consumer", id, beanDefinition);
  94. }
  95. // ========================== 5 对所有标签的普适性处理 ================
  96. Set<String> props = new HashSet<>();
  97. ManagedMap parameters = null;
  98. for (Method setter : beanClass.getMethods()) {
  99. String name = setter.getName();
  100. if (name.length() > 3 && name.startsWith("set")
  101. && Modifier.isPublic(setter.getModifiers())
  102. && setter.getParameterTypes().length == 1) {
  103. Class<?> type = setter.getParameterTypes()[0];
  104. String beanProperty = name.substring(3, 4).toLowerCase() + name.substring(4);
  105. String property = StringUtils.camelToSplitName(beanProperty, "-");
  106. props.add(property);
  107. // check the setter/getter whether match
  108. Method getter = null;
  109. try {
  110. getter = beanClass.getMethod("get" + name.substring(3), new Class<?>[0]);
  111. } catch (NoSuchMethodException e) {
  112. try {
  113. getter = beanClass.getMethod("is" + name.substring(3), new Class<?>[0]);
  114. } catch (NoSuchMethodException e2) {
  115. // ignore, there is no need any log here since some class implement the interface: EnvironmentAware,
  116. // ApplicationAware, etc. They only have setter method, otherwise will cause the error log during application start up.
  117. }
  118. }
  119. if (getter == null
  120. || !Modifier.isPublic(getter.getModifiers())
  121. || !type.equals(getter.getReturnType())) {
  122. continue;
  123. }
  124. if ("parameters".equals(property)) {
  125. parameters = parseParameters(element.getChildNodes(), beanDefinition);
  126. } else if ("methods".equals(property)) {
  127. parseMethods(id, element.getChildNodes(), beanDefinition, parserContext);
  128. } else if ("arguments".equals(property)) {
  129. parseArguments(id, element.getChildNodes(), beanDefinition, parserContext);
  130. } else {
  131. String value = element.getAttribute(property);
  132. if (value != null) {
  133. value = value.trim();
  134. if (value.length() > 0) {
  135. if ("registry".equals(property) && RegistryConfig.NO_AVAILABLE.equalsIgnoreCase(value)) {
  136. RegistryConfig registryConfig = new RegistryConfig();
  137. registryConfig.setAddress(RegistryConfig.NO_AVAILABLE);
  138. beanDefinition.getPropertyValues().addPropertyValue(beanProperty, registryConfig);
  139. } else if ("provider".equals(property) || "registry".equals(property) || ("protocol".equals(property) && ServiceBean.class.equals(beanClass))) {
  140. /**
  141. * For 'provider' 'protocol' 'registry', keep literal value (should be id/name) and set the value to 'registryIds' 'providerIds' protocolIds'
  142. * The following process should make sure each id refers to the corresponding instance, here's how to find the instance for different use cases:
  143. * 1. Spring, check existing bean by id, see{@link ServiceBean#afterPropertiesSet()}; then try to use id to find configs defined in remote Config Center
  144. * 2. API, directly use id to find configs defined in remote Config Center; if all config instances are defined locally, please use {@link org.apache.dubbo.config.ServiceConfig#setRegistries(List)}
  145. */
  146. beanDefinition.getPropertyValues().addPropertyValue(beanProperty + "Ids", value);
  147. } else {
  148. Object reference;
  149. if (isPrimitive(type)) {
  150. if ("async".equals(property) && "false".equals(value)
  151. || "timeout".equals(property) && "0".equals(value)
  152. || "delay".equals(property) && "0".equals(value)
  153. || "version".equals(property) && "0.0.0".equals(value)
  154. || "stat".equals(property) && "-1".equals(value)
  155. || "reliable".equals(property) && "false".equals(value)) {
  156. // backward compatibility for the default value in old version's xsd
  157. value = null;
  158. }
  159. reference = value;
  160. } else if ("onreturn".equals(property)) {
  161. int index = value.lastIndexOf(".");
  162. String returnRef = value.substring(0, index);
  163. String returnMethod = value.substring(index + 1);
  164. reference = new RuntimeBeanReference(returnRef);
  165. beanDefinition.getPropertyValues().addPropertyValue("onreturnMethod", returnMethod);
  166. } else if ("onthrow".equals(property)) {
  167. int index = value.lastIndexOf(".");
  168. String throwRef = value.substring(0, index);
  169. String throwMethod = value.substring(index + 1);
  170. reference = new RuntimeBeanReference(throwRef);
  171. beanDefinition.getPropertyValues().addPropertyValue("onthrowMethod", throwMethod);
  172. } else if ("oninvoke".equals(property)) {
  173. int index = value.lastIndexOf(".");
  174. String invokeRef = value.substring(0, index);
  175. String invokeRefMethod = value.substring(index + 1);
  176. reference = new RuntimeBeanReference(invokeRef);
  177. beanDefinition.getPropertyValues().addPropertyValue("oninvokeMethod", invokeRefMethod);
  178. } else {
  179. if ("ref".equals(property) && parserContext.getRegistry().containsBeanDefinition(value)) {
  180. BeanDefinition refBean = parserContext.getRegistry().getBeanDefinition(value);
  181. if (!refBean.isSingleton()) {
  182. throw new IllegalStateException("The exported service ref " + value + " must be singleton! Please set the " + value + " bean scope to singleton, eg: <bean id=\"" + value + "\" scope=\"singleton\" ...>");
  183. }
  184. }
  185. reference = new RuntimeBeanReference(value);
  186. }
  187. beanDefinition.getPropertyValues().addPropertyValue(beanProperty, reference);
  188. }
  189. }
  190. }
  191. }
  192. }
  193. }
  194. NamedNodeMap attributes = element.getAttributes();
  195. int len = attributes.getLength();
  196. for (int i = 0; i < len; i++) {
  197. Node node = attributes.item(i);
  198. String name = node.getLocalName();
  199. if (!props.contains(name)) {
  200. if (parameters == null) {
  201. parameters = new ManagedMap();
  202. }
  203. String value = node.getNodeValue();
  204. parameters.put(name, new TypedStringValue(value, String.class));
  205. }
  206. }
  207. if (parameters != null) {
  208. beanDefinition.getPropertyValues().addPropertyValue("parameters", parameters);
  209. }
  210. return beanDefinition;
  211. }

重要接口

Invocation.java

  1. //封装RPC远程调用的信息
  2. public interface Invocation {
  3. /**调用方法名称
  4. * get method name.
  5. *
  6. * @return method name.
  7. * @serial
  8. */
  9. String getMethodName();
  10. /**参数类型(行参)
  11. * get parameter types.
  12. *
  13. * @return parameter types.
  14. * @serial
  15. */
  16. Class<?>[] getParameterTypes();
  17. /** 实参
  18. * get arguments.
  19. *
  20. * @return arguments.
  21. * @serial
  22. */
  23. Object[] getArguments();
  24. /**
  25. * get attachments(附件).
  26. *
  27. * @return attachments.
  28. * @serial
  29. */
  30. Map<String, String> getAttachments();
  31. void setAttachment(String key, String value);
  32. void setAttachmentIfAbsent(String key, String value);
  33. /**
  34. * get attachment by key.
  35. *
  36. * @return attachment value.
  37. * @serial
  38. */
  39. String getAttachment(String key);
  40. /**
  41. * get attachment by key with default value.
  42. *
  43. * @return attachment value.
  44. * @serial
  45. */
  46. String getAttachment(String key, String defaultValue);
  47. /** 封装了调用接口
  48. * get the invoker in current context.
  49. *
  50. * @return invoker.
  51. * @transient
  52. */
  53. Invoker<?> getInvoker();
  54. }

Invoker.java

  1. /** 若继承自Node,故可以通过getUrl()方法获取到URL,即,Invoker可以作为Adaptive方法的参数
  2. * 是提供者 provider 的代理对象,在代码中就代表提供者。特别是在消费者进行远程调
  3. * 用时,其通过服务路由、负载均衡、集群容错等机制要查找的就是 Invoker。找到了其需要
  4. * 的 Invoker 实例就可以进行远程调用了。
  5. * */
  6. public interface Invoker<T> extends Node {
  7. /**
  8. * get service interface.
  9. * 调用的接口(服务名称)
  10. * @return service interface.
  11. */
  12. Class<T> getInterface();
  13. /**
  14. * invoke.
  15. * 执行调用并返回结果
  16. * @param invocation
  17. * @return result
  18. * @throws RpcException
  19. */
  20. Result invoke(Invocation invocation) throws RpcException;
  21. }

Exporter.java

  1. /**
  2. * 服务暴露对象。其包含一个很重要的方法 getInvoker(),用于获取当前服务暴露实例所
  3. * 包含的远程调用实例 Invoker,即可以进行的远程调用。
  4. */
  5. public interface Exporter<T> {
  6. /**
  7. * get invoker.
  8. *
  9. * @return invoker
  10. */
  11. Invoker<T> getInvoker();
  12. /**
  13. * unexport. 取消暴露
  14. * <p>
  15. * <code>
  16. * getInvoker().destroy();
  17. * </code>
  18. */
  19. void unexport();
  20. }

Directory.java

  1. // Directory 中包含一个很重要的方法 list()
  2. // 其返回结果为一个 List<Invoker>。
  3. // 可以将Directory理解为,提供某一具体服务的Invoker列表
  4. public interface Directory<T> extends Node {
  5. /**
  6. * get service type.
  7. *
  8. * @return service type.
  9. */
  10. Class<T> getInterface();
  11. /**
  12. * list invokers.
  13. *
  14. * @return invokers
  15. */
  16. List<Invoker<T>> list(Invocation invocation) throws RpcException;
  17. }