Dubbo启动源码解析一

作者: 蓝梅 | 来源:发表于2021-11-06 16:20 被阅读0次

    一、启动入口

    这次讲 dubbo-spring-boot-starter 启动方式,所以入口就是Spring的SPI机制;
    首先在META-INF/spring.factories配置下,配置了org.apache.dubbo.spring.boot.autoconfigure.DubboAutoConfiguration类,在启动时,则会把DubboAutoConfiguration类注册到spring容器中;
    我们来看下DubboAutoConfiguration
    先看启动流程

       @Bean
        public ServiceAnnotationBeanPostProcessor serviceAnnotationBeanPostProcessor(@Qualifier("dubboScanBasePackagesPropertyResolver") PropertyResolver propertyResolver) {
            Set<String> packagesToScan = (Set)propertyResolver.getProperty("base-packages", Set.class, Collections.emptySet());
            return new ServiceAnnotationBeanPostProcessor(packagesToScan);
        }
    

    我们先看下生产者端的启动流程,首先是在Spring中注册ServiceAnnotationBeanPostProcessor类

    二、ServiceAnnotationBeanPostProcessor解析

    我们先看下ServiceAnnotationBeanPostProcessor类 ServiceAnnotationBeanPostProcessor

    该类实现了BeanDefinitionRegistryPostProcessor接口,则在Spring容器初始化时,会调用postProcessBeanDefinitionRegistry方法

        @Override
        public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
            // 注册DubboBootstrapApplicationListener类
            registerBeans(registry, DubboBootstrapApplicationListener.class);
            //获取扫描路径
            Set<String> resolvedPackagesToScan = resolvePackagesToScan(packagesToScan);
            if (!CollectionUtils.isEmpty(resolvedPackagesToScan)) {
                //根据扫描路径去扫描生成实例并注册,且生成相应的ServiceBean对象,且注册到Spring中
                registerServiceBeans(resolvedPackagesToScan, registry);
            } else {
                if (logger.isWarnEnabled()) {
                    logger.warn("packagesToScan is empty , ServiceBean registry will be ignored!");
                }
            }
    
        }
    

    我们会看到,这个时候会去注册DubboBootstrapApplicationListener类,这个类我们等流程到了在分析,我们先按启动流程看过去;resolvePackagesToScan方法先获取到需要扫描的包 ,然后再调用registerServiceBeans去注册相关实例,我们重点来看下registerServiceBeans方法

        private void registerServiceBeans(Set<String> packagesToScan, BeanDefinitionRegistry registry) {
            //new出dubbo的扫描器,主要是继承ClassPathBeanDefinitionScanner,功能几乎一样,只是多了一些获取环境参数的功能
            DubboClassPathBeanDefinitionScanner scanner =
                    new DubboClassPathBeanDefinitionScanner(registry, environment, resourceLoader);
            BeanNameGenerator beanNameGenerator = resolveBeanNameGenerator(registry);
            scanner.setBeanNameGenerator(beanNameGenerator);
            //添加需要扫描的注解(主要是为了兼容以前的版本,还有会扫描alibaba这个包下的)
            scanner.addIncludeFilter(new AnnotationTypeFilter(Service.class));
            scanner.addIncludeFilter(new AnnotationTypeFilter(com.alibaba.dubbo.config.annotation.Service.class));
            for (String packageToScan : packagesToScan) {
    
                // 扫描到的类,就会注册进spring容器
                scanner.scan(packageToScan);
                //获取到刚刚扫描出的类
                Set<BeanDefinitionHolder> beanDefinitionHolders =
                        findServiceBeanDefinitionHolders(scanner, packageToScan, registry, beanNameGenerator);
                if (!CollectionUtils.isEmpty(beanDefinitionHolders)) {
                    //扫描出的打有@Service注解的类,会挨个去生成ServiceBean去注册
                    for (BeanDefinitionHolder beanDefinitionHolder : beanDefinitionHolders) {
                        registerServiceBean(beanDefinitionHolder, registry, scanner);
                    }
                    if (logger.isInfoEnabled()) {
                        logger.info(beanDefinitionHolders.size() + " annotated Dubbo's @Service Components { " +
                                beanDefinitionHolders +
                                " } were scanned under package[" + packageToScan + "]");
                    }
                } else {
                    if (logger.isWarnEnabled()) {
                        logger.warn("No Spring Bean annotating Dubbo's @Service was found under package["
                                + packageToScan + "]");
                    }
                }
            }
        }
    

    接下来,我们主要去看下registerServiceBean方法

        private void registerServiceBean(BeanDefinitionHolder beanDefinitionHolder, BeanDefinitionRegistry registry,
                                         DubboClassPathBeanDefinitionScanner scanner) {
            Class<?> beanClass = resolveClass(beanDefinitionHolder);
            Annotation service = findServiceAnnotation(beanClass);
            //获取当前对象的注解参数
            AnnotationAttributes serviceAnnotationAttributes = getAnnotationAttributes(service, false, false);
            //获取接口类型
            Class<?> interfaceClass = resolveServiceInterfaceClass(serviceAnnotationAttributes, beanClass);
            String annotatedServiceBeanName = beanDefinitionHolder.getBeanName();
            //构建serviceBean bean定义
            AbstractBeanDefinition serviceBeanDefinition =
                    buildServiceBeanDefinition(service, serviceAnnotationAttributes, interfaceClass, annotatedServiceBeanName);
            // 生成ServiceBean在Spring容器中的名称(ServiceBean:接口全限定名+分组+版本)
            String beanName = generateServiceBeanName(serviceAnnotationAttributes, interfaceClass);
            //注册ServiceBean
            if (scanner.checkCandidate(beanName, serviceBeanDefinition)) { // check duplicated candidate bean
                registry.registerBeanDefinition(beanName, serviceBeanDefinition);
    
                if (logger.isInfoEnabled()) {
                    logger.info("The BeanDefinition[" + serviceBeanDefinition +
                            "] of ServiceBean has been registered with name : " + beanName);
                }
            } else {
                if (logger.isWarnEnabled()) {
                    logger.warn("The Duplicated BeanDefinition[" + serviceBeanDefinition +
                            "] of ServiceBean[ bean name : " + beanName +
                            "] was be found , Did @DubboComponentScan scan to same package in many times?");
                }
            }
        }
    

    接下来,我们来看下buildServiceBeanDefinition方法

        private AbstractBeanDefinition buildServiceBeanDefinition(Annotation serviceAnnotation,
                                                                  AnnotationAttributes serviceAnnotationAttributes,
                                                                  Class<?> interfaceClass,
                                                                  String annotatedServiceBeanName) {
            //生成ServiceBean bean定义对象
            BeanDefinitionBuilder builder = rootBeanDefinition(ServiceBean.class);
            AbstractBeanDefinition beanDefinition = builder.getBeanDefinition();
            MutablePropertyValues propertyValues = beanDefinition.getPropertyValues();
            //排除不需要设置的属性
            String[] ignoreAttributeNames = of("provider", "monitor", "application", "module", "registry", "protocol",
                    "interface", "interfaceName", "parameters");
            propertyValues.addPropertyValues(new AnnotationPropertyValuesAdapter(serviceAnnotation, environment, ignoreAttributeNames));
            // 设置ref对象,addPropertyReference则会根据名称在Spring容器中找到相应的对象注入进去
            addPropertyReference(builder, "ref", annotatedServiceBeanName);
            // 以下都是设置ServiceBean 属性,主要是从@Service注解参数中获取
            builder.addPropertyValue("interface", interfaceClass.getName());
            // Convert parameters into map
            builder.addPropertyValue("parameters", convertParameters(serviceAnnotationAttributes.getStringArray("parameters")));
            // Add methods parameters
            List<MethodConfig> methodConfigs = convertMethodConfigs(serviceAnnotationAttributes.get("methods"));
            if (!methodConfigs.isEmpty()) {
                builder.addPropertyValue("methods", methodConfigs);
            }
            /**
             * Add {@link org.apache.dubbo.config.ProviderConfig} Bean reference
             */
            String providerConfigBeanName = serviceAnnotationAttributes.getString("provider");
            if (StringUtils.hasText(providerConfigBeanName)) {
                addPropertyReference(builder, "provider", providerConfigBeanName);
            }
            /**
             * Add {@link org.apache.dubbo.config.MonitorConfig} Bean reference
             */
            String monitorConfigBeanName = serviceAnnotationAttributes.getString("monitor");
            if (StringUtils.hasText(monitorConfigBeanName)) {
                addPropertyReference(builder, "monitor", monitorConfigBeanName);
            }
            /**
             * Add {@link org.apache.dubbo.config.ApplicationConfig} Bean reference
             */
            String applicationConfigBeanName = serviceAnnotationAttributes.getString("application");
            if (StringUtils.hasText(applicationConfigBeanName)) {
                addPropertyReference(builder, "application", applicationConfigBeanName);
            }
            /**
             * Add {@link org.apache.dubbo.config.ModuleConfig} Bean reference
             */
            String moduleConfigBeanName = serviceAnnotationAttributes.getString("module");
            if (StringUtils.hasText(moduleConfigBeanName)) {
                addPropertyReference(builder, "module", moduleConfigBeanName);
            }
            /**
             * Add {@link org.apache.dubbo.config.RegistryConfig} Bean reference
             */
            String[] registryConfigBeanNames = serviceAnnotationAttributes.getStringArray("registry");
            List<RuntimeBeanReference> registryRuntimeBeanReferences = toRuntimeBeanReferences(registryConfigBeanNames);
            if (!registryRuntimeBeanReferences.isEmpty()) {
                builder.addPropertyValue("registries", registryRuntimeBeanReferences);
            }
            /**
             * Add {@link org.apache.dubbo.config.ProtocolConfig} Bean reference
             */
            String[] protocolConfigBeanNames = serviceAnnotationAttributes.getStringArray("protocol");
            List<RuntimeBeanReference> protocolRuntimeBeanReferences = toRuntimeBeanReferences(protocolConfigBeanNames);
            if (!protocolRuntimeBeanReferences.isEmpty()) {
                builder.addPropertyValue("protocols", protocolRuntimeBeanReferences);
            }
            return builder.getBeanDefinition();
        }
    

    到这,ServiceBean注册成功,ServiceBean类很重要,每个Dubbo service实例都对应一个ServiceBean,相关配置都在ServiceBean中;我们再回到开始注册的DubboBootstrapApplicationListener类

    三、DubboBootstrapApplicationListener解析

    DubboBootstrapApplicationListener

    DubboBootstrapApplicationListener类继承了OneTimeExecutionApplicationContextEventListener,OneTimeExecutionApplicationContextEventListener实现了ApplicationListener,主要监听了Spring容器生命周期,我们看下onApplicationContextEvent方法

        @Override
        public void onApplicationContextEvent(ApplicationContextEvent event) {
            if (event instanceof ContextRefreshedEvent) {
                onContextRefreshedEvent((ContextRefreshedEvent) event);
            } else if (event instanceof ContextClosedEvent) {
                onContextClosedEvent((ContextClosedEvent) event);
            }
        }
    
        private void onContextRefreshedEvent(ContextRefreshedEvent event) {
            dubboBootstrap.start();
        }
    

    我们可以看到,当Spring容器启动成功时,会调用dubboBootstrap.start();

        public DubboBootstrap start() {
            if (started.compareAndSet(false, true)) {
                //初始化 DubboBootstrap 
                initialize();
                if (logger.isInfoEnabled()) {
                    logger.info(NAME + " is starting...");
                }
                // 1. 导出服务
                exportServices();
                // Not only provider register
                if (!isOnlyRegisterProvider() || hasExportedServices()) {
                    // 导出服务元数据
                    exportMetadataService();
                    //注册服务实例
                    registerServiceInstance();
                }
                //消费端引用服务
                referServices();
                if (logger.isInfoEnabled()) {
                    logger.info(NAME + " has started.");
                }
            }
            return this;
        }
    
        private void exportServices() {
            configManager.getServices().forEach(sc -> {
                ServiceConfig serviceConfig = (ServiceConfig) sc;
                serviceConfig.setBootstrap(this);
    
                if (exportAsync) {
                    ExecutorService executor = executorRepository.getServiceExporterExecutor();
                    Future<?> future = executor.submit(() -> {
                        //导出服务,调用每个注册的ServiceBean的export方法去导出
                        sc.export();
                    });
                    asyncExportingFutures.add(future);
                } else {
                    sc.export();
                    exportedServices.add(sc);
                }
            });
        }
    

    接下来,主要逻辑在ServiceBean中,这个export方法在其父类ServiceConfig中,我们下一篇主要讲ServiceConfig逻辑;

    相关文章

      网友评论

        本文标题:Dubbo启动源码解析一

        本文链接:https://www.haomeiwen.com/subject/eodjzltx.html