ダボソースコードシリーズ3-ダボスタートBean生成

ダボのソースコードシリーズ1から、 ダボ の全体的なアーキテクチャ設計について学びました。以下では、ダボが起動時に独自のBeanをロードするためにSpringBootにシームレスに接続される方法について詳しく説明します。

ダボ起動方式

1.スタンドアロンモード:Mainメソッドを介してSpringブートをロードします

2.コンテナから開始します。Tomcat、桟橋などを介して開始するには、Springをロードします。

これらの2つのスタートアップ方法は、Springスタートアップに統合して独自のBeanをロードすることです。DubboはSpringの拡張性を利用し、独自のスタートアッププロセスをSpringスタートアップにシームレスに統合します。

ダボの起動プロセス

次の図に示すように、Webコンテナはdubboに継承されないため、デフォルトではスタンドアロンモードで開始され、入り口はMainメソッドである必要があります。

Mainクラスのmainメソッドは、最終的にコンテナのstartメソッドを呼び出してコンテナを起動します。ここでのコンテナには、Log4jContainer、LogbackContainer、SpringContainerが含まれます。これらのコンテナの機能は名前からわかります。

Log4jContainerおよびLogbackContainer:ログ構成機能

SpringContainer:Springコンテナの開始

SpringContainerのstartメソッドは、spring startを有効にすることです。コードは、次のとおりです。

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はspring.schemas、spring.handlers、およびdubbo.xsdファイルをカスタマイズします 次の図に示すように、Springカスタムタグを参照してください

MATE-INF / spring.schemasファイル:

MATE-INF / spring.handlers文件:

MATE-INF / dubbo.xsdファイル:

Spring.schemas、spring.handlers、およびその他のファイルの内容はSpringの起動時に読み込まれ、dubbo独自の名前空間ハンドラーDubboNamespaceHandlerがdubboのMATE-INF / spring.handlersで定義さます。SpringがBeanを読み込むと、dubbo名前空間が検出されます。DubboNamespaceHandler dubboタグを持つクラスを解析および処理するために呼び出されます。主要なプロセスは次のとおりです。

1. AbstractXmlApplicationContextのloadBeanDefinitionsメソッドは、MATE-INF /spring.handlersのすべての空間プロセッサーをロードします

2. DefaultBeanDefinitionDocumentReaderのparseBeanDefinitionsメソッドは、それがデフォルトのスペースであるかどうかに応じて、parseelementメソッドの呼び出しを制御します。

デフォルトのスペース: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の解析メソッドを呼び出すためのものです。コードは次のとおりです。

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メソッドは、ServiceConfig、ReferenceConfig、ApplicationConfig、RegistryConfig、MetadataReportConfig、MonitorConfig、ProviderConfig、ConsumerConfig、ProtocolConfig、ConfigCenterConfig、およびその他の対応するBeanDefinitionsをDubboに実装します。これらのBeanDefinitionsはSpringコンテナーに登録され、Springコンテナーに渡されてすべてのBeanを均一に管理します。 。

Springコンテナは最終的にClassPathXmlApplicationContextクラスのgetBeanメソッドを呼び出し、BeanDefinitionを対応するBeanオブジェクト変換します。 

参照:

https://www.jianshu.com/p/16b72c10fca8

https://segmentfault.com/a/1190000007047168

https://blog.csdn.net/MrZhangXL/article/details/78636494

おすすめ

転載: blog.csdn.net/ywlmsm1224811/article/details/102590449