美文网首页
nacos服务注册--dubbo-spring-boot

nacos服务注册--dubbo-spring-boot

作者: skipper_shou | 来源:发表于2020-10-30 18:39 被阅读0次

    dubbo-spring-boot-autoconfigure-compatible中注入ServiceAnnotationBeanPostProcessor进行初始化,ServiceAnnotationBeanPostProcessor继承了ServiceClassPostProcessor,ServiceClassPostProcessor实现了BeanDefinitionRegistryPostProcessor中的方法postProcessBeanDefinitionRegistry
    再看org.springframework.context.support.AbstractApplicationContext#refresh中的invokeBeanFactoryPostProcessors(beanFactory)用来找出所有beanFactory后置处理器,并且调用这些处理器来改变bean的定义。
    invokeBeanFactoryPostProcessors(beanFactory)实际上是委托org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());方法处理的。
    PostProcessorRegistrationDelegateinvokeBeanFactoryPostProcessors方法调用了BeanDefinitionRegistryPostProcessorpostProcessBeanDefinitionRegistry接口,所有实现postProcessBeanDefinitionRegistry接口的bean都会被调用,包括ServiceClassPostProcessor,这里初始化了DubboBootstrapApplicationListener,当监听到ContextRefreshedEvent事件之后,触发dubbo服务启动dubboBootstrap.start(),调用ServiceConfig.export(),这个方法会启动一个网络监听,从而实现服务发布。具体怎么实现服务发布会在之后的文章做介绍

    public class DubboAutoConfiguration {
      
    
        @ConditionalOnProperty(prefix = DUBBO_SCAN_PREFIX, name = BASE_PACKAGES_PROPERTY_NAME)
        @ConditionalOnBean(name = BASE_PACKAGES_PROPERTY_RESOLVER_BEAN_NAME)
        @Bean
        public ServiceAnnotationBeanPostProcessor serviceAnnotationBeanPostProcessor(
                @Qualifier(BASE_PACKAGES_PROPERTY_RESOLVER_BEAN_NAME) PropertyResolver propertyResolver) {
            Set<String> packagesToScan = propertyResolver.getProperty(BASE_PACKAGES_PROPERTY_NAME, Set.class, emptySet());
            return new ServiceAnnotationBeanPostProcessor(packagesToScan);
        }
    
        ......
    }
    
    public class ServiceAnnotationBeanPostProcessor extends ServiceClassPostProcessor {
        
        public ServiceAnnotationBeanPostProcessor(String... packagesToScan) {
            this(Arrays.asList(packagesToScan));
        }
    
        public ServiceAnnotationBeanPostProcessor(Collection<String> packagesToScan) {
            this(new LinkedHashSet<>(packagesToScan));
        }
    
        public ServiceAnnotationBeanPostProcessor(Set<String> packagesToScan) {
            super(packagesToScan);
        }
    
    }
    
    public class ServiceClassPostProcessor implements BeanDefinitionRegistryPostProcessor, EnvironmentAware,
            ResourceLoaderAware, BeanClassLoaderAware {
    
        @Override
        public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
    
            // @since 2.7.5
            registerBeans(registry, DubboBootstrapApplicationListener.class);
    
            Set<String> resolvedPackagesToScan = resolvePackagesToScan(packagesToScan);
    
            if (!CollectionUtils.isEmpty(resolvedPackagesToScan)) {
                registerServiceBeans(resolvedPackagesToScan, registry);
            } else {
                if (logger.isWarnEnabled()) {
                    logger.warn("packagesToScan is empty , ServiceBean registry will be ignored!");
                }
            }
    
        }
    
        ......
    
    }
    
    public abstract class AbstractApplicationContext extends DefaultResourceLoader
            implements ConfigurableApplicationContext, DisposableBean {
    
        ......
    
        @Override
        public void refresh() throws BeansException, IllegalStateException {
            synchronized (this.startupShutdownMonitor) {
                // Prepare this context for refreshing.
                prepareRefresh();
    
                // Tell the subclass to refresh the internal bean factory.
                ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
    
                // Prepare the bean factory for use in this context.
                prepareBeanFactory(beanFactory);
    
                try {
                    // Allows post-processing of the bean factory in context subclasses.
                    postProcessBeanFactory(beanFactory);
    
                    // Invoke factory processors registered as beans in the context.
                    invokeBeanFactoryPostProcessors(beanFactory);
    
                    // Register bean processors that intercept bean creation.
                    registerBeanPostProcessors(beanFactory);
    
                    // Initialize message source for this context.
                    initMessageSource();
    
                    // Initialize event multicaster for this context.
                    initApplicationEventMulticaster();
    
                    // Initialize other special beans in specific context subclasses.
                    onRefresh();
    
                    // Check for listener beans and register them.
                    registerListeners();
    
                    // Instantiate all remaining (non-lazy-init) singletons.
                    finishBeanFactoryInitialization(beanFactory);
    
                    // Last step: publish corresponding event.
                    finishRefresh();
                }
    
                catch (BeansException ex) {
                    if (logger.isWarnEnabled()) {
                        logger.warn("Exception encountered during context initialization - " +
                                "cancelling refresh attempt: " + ex);
                    }
    
                    // Destroy already created singletons to avoid dangling resources.
                    destroyBeans();
    
                    // Reset 'active' flag.
                    cancelRefresh(ex);
    
                    // Propagate exception to caller.
                    throw ex;
                }
    
                finally {
                    // Reset common introspection caches in Spring's core, since we
                    // might not ever need metadata for singleton beans anymore...
                    resetCommonCaches();
                }
            }
        }
    
        ......
    
        protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
            PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());
    
            // Detect a LoadTimeWeaver and prepare for weaving, if found in the meantime
            // (e.g. through an @Bean method registered by ConfigurationClassPostProcessor)
            if (beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
                beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
                beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
            }
        }
        
    }
    
    class PostProcessorRegistrationDelegate {
        public static void invokeBeanFactoryPostProcessors(
                ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {
    
            // Invoke BeanDefinitionRegistryPostProcessors first, if any.
            Set<String> processedBeans = new HashSet<String>();
    
            if (beanFactory instanceof BeanDefinitionRegistry) {
                BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
                List<BeanFactoryPostProcessor> regularPostProcessors = new LinkedList<BeanFactoryPostProcessor>();
                List<BeanDefinitionRegistryPostProcessor> registryProcessors = new LinkedList<BeanDefinitionRegistryPostProcessor>();
    
                for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
                    if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
                        BeanDefinitionRegistryPostProcessor registryProcessor =
                                (BeanDefinitionRegistryPostProcessor) postProcessor;
                        registryProcessor.postProcessBeanDefinitionRegistry(registry);
                        registryProcessors.add(registryProcessor);
                    }
                    else {
                        regularPostProcessors.add(postProcessor);
                    }
                }
            }
        }
        ......
    }
    
    public class ServiceClassPostProcessor implements BeanDefinitionRegistryPostProcessor, EnvironmentAware,
            ResourceLoaderAware, BeanClassLoaderAware {
    
        @Override
        public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
    
            // @since 2.7.5
            registerBeans(registry, DubboBootstrapApplicationListener.class);
    
            Set<String> resolvedPackagesToScan = resolvePackagesToScan(packagesToScan);
    
            if (!CollectionUtils.isEmpty(resolvedPackagesToScan)) {
                registerServiceBeans(resolvedPackagesToScan, registry);
            } else {
                if (logger.isWarnEnabled()) {
                    logger.warn("packagesToScan is empty , ServiceBean registry will be ignored!");
                }
            }
    
        }
    
    }
    
    public class DubboBootstrapApplicationListener extends OneTimeExecutionApplicationContextEventListener
            implements Ordered {
    
        @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();
        }
    
    }
    

    相关文章

      网友评论

          本文标题:nacos服务注册--dubbo-spring-boot

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