从 dubbo源码系列1 我们了解了 dubbo 的总体架构设计,下面详细讲解 dubbo 启动时是怎样无缝对接 spring 启动加载自己的 bean
dubbo启动方式
1、standlone模式: 通过 Main 方法加载 Spring 启动
2、使用容器启动: 通过 tomcat、 jetty 等加载 Spring 启动
这两种方式的启动都是为了融合到 spring 启动中来加载自己的bean,dubbo正是利用了 spring 的扩展性,将自己的启动流程无缝的融合到了 spring 启动中去
dubbo启动过程
dubbo 中没有继承web容器,因此默认使用的是 standlone模式启动,入口肯定是 Main 方法,如下图:
Main 类中的 main 方法最终调用 container 的 start 方法启动容器,这里的 container 有 Log4jContainer 、LogbackContainer 和 SpringContainer,从名字就可以看出这些container的功能
Log4jContainer 和 LogbackContainer :日志配置功能
SpringContainer:spring容器启动
SpringContainer 的 start 方法就是开启了 spring 启动,代码如下:
public class SpringContainer implements Container {
public static final String SPRING_CONFIG = "dubbo.spring.config";
public static final String DEFAULT_SPRING_CONFIG = "classpath*:META-INF/spring/*.xml";
private static final Logger logger = LoggerFactory.getLogger(SpringContainer.class);
static ClassPathXmlApplicationContext context;
public static ClassPathXmlApplicationContext getContext() {
return context;
}
@Override
public void start() {
// 加载 dubbo.spring.config 配置路径下的所有文件
String configPath = ConfigUtils.getProperty(SPRING_CONFIG);
if (StringUtils.isEmpty(configPath)) {
// 默认加载 classpath*:META-INF/spring/*.xml 路径下的所有文件
configPath = DEFAULT_SPRING_CONFIG;
}
context = new ClassPathXmlApplicationContext(configPath.split("[,\\s]+"), false);
// spring 加载bean
context.refresh();
context.start();
}
@Override
public void stop() {
try {
if (context != null) {
context.stop();
context.close();
context = null;
}
} catch (Throwable e) {
logger.error(e.getMessage(), e);
}
}
}
这里调用了 AbstractApplicationContext 的 refresh 方法,此方法就是 Spring 启动加载bean实现的整个过程,dubbo 在这其中正是利用了 Spring 自定义标签拓展功能,dubbo 在 MATE-INF 目录下自定义配置了 spring.schemas 、spring.handlers 和 dubbo.xsd 文件,参照 spring自定义标签 ,如下图所示:
MATE-INF/spring.schemas 文件:
MATE-INF/spring.handlers 文件:
MATE-INF/dubbo.xsd 文件:
Spring 启动过程中会加载 spring.schemas 、spring.handlers 等文件内容,而在dubbo的 MATE-INF/spring.handlers 定义了dubbo自己的命名空间处理器,即 DubboNamespaceHandler,当 Spring 加载bean遇到 dubbo 命名空间时会调用 DubboNamespaceHandler 来解析处理具有 dubbo 标签的类,关键流程如下图:
1、AbstractXmlApplicationContext 的 loadBeanDefinitions 方法加载了 MATE-INF/spring.handlers 所有的空间处理器:
2、DefaultBeanDefinitionDocumentReader 的 parseBeanDefinitions 方法根据是否是默认空间来控制调用解析元素方法
默认空间:http://www.springframework.org/schema/beans,调用 parseDefaultElement 方法解析元素
非默认空间:http://dubbo.apache.org/schema/dubbo,调用 BeanDefinitionParserDelegate 的 parseCustomElement 方法解析自定义的命名空间元素
3、DefaultNamespaceHandlerResolver 的 resolve 方法根据命名空间获取对应的空间处理器,尔后调用 NamespaceHandler 的 init 方法
接下来我们看一下 dubbo 中定义的 DubboNamespaceHandler 类,如下图:
DubboNamespaceHandler 的 init 方法主要工作是将 自定义元素 和 自定义解析器(DubboBeanDefinitionParser)的对应关系注册到解析器缓存中,注册自定义解析器之后,就是调用 DubboBeanDefinitionParser(自定义解析器) 的 parse 方法解析xml元素生成BeanDefinition ,流程如下图:
这里就是调用 DubboBeanDefinitionParser 的 parse 方法 ,代码如下:
private static BeanDefinition parse(Element element, ParserContext parserContext, Class<?> beanClass, boolean required) {
RootBeanDefinition beanDefinition = new RootBeanDefinition();
beanDefinition.setBeanClass(beanClass);
beanDefinition.setLazyInit(false);
String id = element.getAttribute("id");
if (StringUtils.isEmpty(id) && required) {
String generatedBeanName = element.getAttribute("name");
if (StringUtils.isEmpty(generatedBeanName)) {
if (ProtocolConfig.class.equals(beanClass)) {
generatedBeanName = "dubbo";
} else {
generatedBeanName = element.getAttribute("interface");
}
}
if (StringUtils.isEmpty(generatedBeanName)) {
generatedBeanName = beanClass.getName();
}
id = generatedBeanName;
int counter = 2;
while (parserContext.getRegistry().containsBeanDefinition(id)) {
id = generatedBeanName + (counter++);
}
}
if (StringUtils.isNotEmpty(id)) {
if (parserContext.getRegistry().containsBeanDefinition(id)) {
throw new IllegalStateException("Duplicate spring bean id " + id);
}
// bean 注册到Spring容器缓存中,以便Spring管理bean
parserContext.getRegistry().registerBeanDefinition(id, beanDefinition);
beanDefinition.getPropertyValues().addPropertyValue("id", id);
}
if (ProtocolConfig.class.equals(beanClass)) {
// ProtocolConfig bean 生成
for (String name : parserContext.getRegistry().getBeanDefinitionNames()) {
BeanDefinition definition = parserContext.getRegistry().getBeanDefinition(name);
PropertyValue property = definition.getPropertyValues().getPropertyValue("protocol");
if (property != null) {
Object value = property.getValue();
if (value instanceof ProtocolConfig && id.equals(((ProtocolConfig) value).getName())) {
definition.getPropertyValues().addPropertyValue("protocol", new RuntimeBeanReference(id));
}
}
}
} else if (ServiceBean.class.equals(beanClass)) {
// ServiceBean bean 生成
String className = element.getAttribute("class");
if (className != null && className.length() > 0) {
RootBeanDefinition classDefinition = new RootBeanDefinition();
classDefinition.setBeanClass(ReflectUtils.forName(className));
classDefinition.setLazyInit(false);
parseProperties(element.getChildNodes(), classDefinition);
beanDefinition.getPropertyValues().addPropertyValue("ref", new BeanDefinitionHolder(classDefinition, id + "Impl"));
}
} else if (ProviderConfig.class.equals(beanClass)) {
// ProviderConfig bean 生成
parseNested(element, parserContext, ServiceBean.class, true, "service", "provider", id, beanDefinition);
} else if (ConsumerConfig.class.equals(beanClass)) {
// ConsumerConfig bean 生成
parseNested(element, parserContext, ReferenceBean.class, false, "reference", "consumer", id, beanDefinition);
}
Set<String> props = new HashSet<>();
ManagedMap parameters = null;
// 类的属性设置
for (Method setter : beanClass.getMethods()) {
String name = setter.getName();
if (name.length() > 3 && name.startsWith("set")
&& Modifier.isPublic(setter.getModifiers())
&& setter.getParameterTypes().length == 1) {
Class<?> type = setter.getParameterTypes()[0];
String beanProperty = name.substring(3, 4).toLowerCase() + name.substring(4);
String property = StringUtils.camelToSplitName(beanProperty, "-");
props.add(property);
// check the setter/getter whether match
Method getter = null;
try {
getter = beanClass.getMethod("get" + name.substring(3), new Class<?>[0]);
} catch (NoSuchMethodException e) {
try {
getter = beanClass.getMethod("is" + name.substring(3), new Class<?>[0]);
} catch (NoSuchMethodException e2) {
// ignore, there is no need any log here since some class implement the interface: EnvironmentAware,
// ApplicationAware, etc. They only have setter method, otherwise will cause the error log during application start up.
}
}
if (getter == null
|| !Modifier.isPublic(getter.getModifiers())
|| !type.equals(getter.getReturnType())) {
continue;
}
if ("parameters".equals(property)) {
parameters = parseParameters(element.getChildNodes(), beanDefinition);
} else if ("methods".equals(property)) {
parseMethods(id, element.getChildNodes(), beanDefinition, parserContext);
} else if ("arguments".equals(property)) {
parseArguments(id, element.getChildNodes(), beanDefinition, parserContext);
} else {
String value = element.getAttribute(property);
if (value != null) {
value = value.trim();
if (value.length() > 0) {
if ("registry".equals(property) && RegistryConfig.NO_AVAILABLE.equalsIgnoreCase(value)) {
RegistryConfig registryConfig = new RegistryConfig();
registryConfig.setAddress(RegistryConfig.NO_AVAILABLE);
beanDefinition.getPropertyValues().addPropertyValue(beanProperty, registryConfig);
} else if ("provider".equals(property) || "registry".equals(property) || ("protocol".equals(property) && ServiceBean.class.equals(beanClass))) {
/**
* For 'provider' 'protocol' 'registry', keep literal value (should be id/name) and set the value to 'registryIds' 'providerIds' protocolIds'
* The following process should make sure each id refers to the corresponding instance, here's how to find the instance for different use cases:
* 1. Spring, check existing bean by id, see{@link ServiceBean#afterPropertiesSet()}; then try to use id to find configs defined in remote Config Center
* 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)}
*/
beanDefinition.getPropertyValues().addPropertyValue(beanProperty + "Ids", value);
} else {
Object reference;
if (isPrimitive(type)) {
if ("async".equals(property) && "false".equals(value)
|| "timeout".equals(property) && "0".equals(value)
|| "delay".equals(property) && "0".equals(value)
|| "version".equals(property) && "0.0.0".equals(value)
|| "stat".equals(property) && "-1".equals(value)
|| "reliable".equals(property) && "false".equals(value)) {
// backward compatibility for the default value in old version's xsd
value = null;
}
reference = value;
} else if(ONRETURN.equals(property) || ONTHROW.equals(property) || ONINVOKE.equals(property)) {
int index = value.lastIndexOf(".");
String ref = value.substring(0, index);
String method = value.substring(index + 1);
reference = new RuntimeBeanReference(ref);
beanDefinition.getPropertyValues().addPropertyValue(property + METHOD, method);
} else {
if ("ref".equals(property) && parserContext.getRegistry().containsBeanDefinition(value)) {
BeanDefinition refBean = parserContext.getRegistry().getBeanDefinition(value);
if (!refBean.isSingleton()) {
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\" ...>");
}
}
reference = new RuntimeBeanReference(value);
}
beanDefinition.getPropertyValues().addPropertyValue(beanProperty, reference);
}
}
}
}
}
}
NamedNodeMap attributes = element.getAttributes();
int len = attributes.getLength();
for (int i = 0; i < len; i++) {
Node node = attributes.item(i);
String name = node.getLocalName();
if (!props.contains(name)) {
if (parameters == null) {
parameters = new ManagedMap();
}
String value = node.getNodeValue();
parameters.put(name, new TypedStringValue(value, String.class));
}
}
if (parameters != null) {
beanDefinition.getPropertyValues().addPropertyValue("parameters", parameters);
}
return beanDefinition;
}
parse 方法实现了 Dubbo 中的 ServiceConfig、ReferenceConfig、ApplicationConfig、RegistryConfig、MetadataReportConfig、MonitorConfig、ProviderConfig、ConsumerConfig、ProtocolConfig、ConfigCenterConfig等 对应的 BeanDefinition,这些 BeanDefinition 注册到Spring容器中,交给Spring容器统一管理所有的bean。
Spring 容器最终 调用 ClassPathXmlApplicationContext 类的 getBean 方法,将 BeanDefinition 转换成对应的 bean 对象
参考:
https://www.jianshu.com/p/16b72c10fca8