In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces "how to use Dubbo and Spring to integrate parsing configuration files". In daily operation, I believe many people have doubts about how to use Dubbo and Spring to integrate parsing configuration files. Xiaobian consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the doubts of "how to integrate parsing configuration files with Dubbo and Spring". Next, please follow the editor to study!
1. Dubbo consumer invocation service provider example
The Dubbo source code analyzed in this column is based on version 2.6.x.
Public class Consumer {public static void main (String [] args) {ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext (new String [] {"META-INF/spring/dubbo-demo-consumer.xml"}); context.start (); DemoService demoService = (DemoService) context.getBean ("demoService"); while (true) {try {Thread.sleep (1000) String hello = demoService.sayHello ("world"); System.out.println (hello);} catch (Throwable throwable) {throwable.printStackTrace ();} public class Provider {public static void main (String [] args) throws Exception {System.setProperty ("java.net.preferIPv4Stack", "true") ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext (new String [] {"META-INF/spring/dubbo-demo-provider.xml"}); context.start (); System.in.read ();}} 2. Spring parses the dubbo configuration file
starts the service provider first, and then the consumer, and finds that the console can output normally. Let's take a look at how Spring parses the configuration files of dubbo consumers and service providers. The Spring container provides the IOC function to generate bean for us. Typically, we put the definition of bean in the xml file, and let's analyze the process of Spring loading the xml configuration file and generating the bean. There are two types of containers provided by Spring: BeanFactory and ApplicationContext. Where BeanFactory is lazy loading, that is, delayed initialization, it initializes the bean when you call getBean, while ApplicationContext loads the non-delayed initialization bean when it initializes the container. First, give a brief overview of the process of generating bean from the Spring container, first encapsulate the information of the bean into BeanDefinition through the loadBeanDefinition process, and then create a bean based on these BeanDefinition. Let's take a look at Spring's process of parsing Dubbo's configuration file and generating bean.
/ / 1. When the Spring container is initialized during new ClassPathXmlApplicationContext, the loadBeanDefinition method will be called to load and parse the xml configuration file context = new ClassPathXmlApplicationContext (new String [] {"META-INF/spring/dubbo-demo-provider.xml"}); / / 2. Loading the configuration file will eventually end here protected void parseBeanDefinitions (Element root, BeanDefinitionParserDelegate delegate) {if (delegate.isDefaultNamespace (root)) {NodeList nl = root.getChildNodes () / / 3. In fact, the xml file has been parsed into Document through dom4j, and a configuration in xml has been parsed into Node to read and process. For (int I = 0; I
< nl.getLength(); i++) { Node node = nl.item(i); if (node instanceof Element) { Element ele = (Element) node; // 4、判断是否是Spring默认可以处理的Node.这里看下面截图,由于dubbo:application, // 是dubbo中定义的,不属于Spring的命名空间管理 if (delegate.isDefaultNamespace(ele)) { parseDefaultElement(ele, delegate); } else { delegate.parseCustomElement(ele); } } } }} public BeanDefinition parseCustomElement(Element ele, BeanDefinition containingBd) { // http://dubbo.apache.org/schema/dubbo String namespaceUri = getNamespaceURI(ele); // DubboNameSpaceHandler NamespaceHandler handler = this.readerContext.getNamespaceHandlerResolver().resolve(namespaceUri); if (handler == null) { return null; } return handler.parse(ele, new ParserContext(this.readerContext, this, containingBd));}private static BeanDefinition parse(Element element, ParserContext parserContext, Class beanClass, boolean required) { RootBeanDefinition beanDefinition = new RootBeanDefinition(); // class com.alibaba.dubbo.config.ApplicationConfig beanDefinition.setBeanClass(beanClass); beanDefinition.setLazyInit(false); // 解析id属性 String id = element.getAttribute("id"); if ((id == null || id.length() == 0) && required) { String generatedBeanName = element.getAttribute("name"); if (generatedBeanName == null || generatedBeanName.length() == 0) { if (ProtocolConfig.class.equals(beanClass)) { generatedBeanName = "dubbo"; } else { generatedBeanName = element.getAttribute("interface"); } } if (generatedBeanName == null || generatedBeanName.length() == 0) { generatedBeanName = beanClass.getName(); } id = generatedBeanName; int counter = 2; while (parserContext.getRegistry().containsBeanDefinition(id)) { id = generatedBeanName + (counter++); } } if (id != null && id.length() >0) {if (parserContext.getRegistry () .containsBeanDefinition (id)) {throw new IllegalStateException ("Duplicate spring bean id" + id);} / / register BeanDefinition parserContext.getRegistry () .registerBeanDefinition (id, beanDefinition) / / put the id attribute into the beanDefinition. When getBean creates the bean, the bean is created based on these attributes. / / the bean created here is ApplicationConfig beanDefinition.getPropertyValues () .addPropertyValue ("id", id). } / / Delete some code. Reference is the value obtained by parsing. It can be seen that the attribute and attribute value are put into BeanDefinition beanDefinition.getPropertyValues (). AddPropertyValue (property, reference); return beanDefinition;}
This is the end of parsing. Spring parses the application node in xml into a BeanDefinition and registers it with Registry. Registry is a Map. Let's analyze the process of creating this ApplicationConfig by Spring.
3. Spring creates ApplicationConfigcontext = new ClassPathXmlApplicationContext (new String [] {"META-INF/spring/dubbo-demo-provider.xml"}); / / the initialization process of the Spring container. After new ClassPathXmlApplicationContext, you will come here public void refresh () throws BeansException, IllegalStateException {synchronized (this.startupShutdownMonitor) {prepareRefresh () / / the above analysis process will be performed here, calling loadBeanDefinition to parse BeanDefinition ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory (); prepareBeanFactory (beanFactory); try {postProcessBeanFactory (beanFactory); invokeBeanFactoryPostProcessors (beanFactory); registerBeanPostProcessors (beanFactory) InitMessageSource (); initApplicationEventMulticaster (); onRefresh (); registerListeners (); / / Instantiate all remaining (non-lazy-init) singletons. You can see that the non-delayed loading bean is initialized after the Spring container initialization / /. Here you will go to the preInstantiasteSingletons method finishBeanFactoryInitialization (beanFactory); finishRefresh ();} in the following figure
/ / Spring creating bean will eventually come to this protected Object doCreateBean (final String beanName, final RootBeanDefinition mbd, final Object [] args) throws BeanCreationException {BeanWrapper instanceWrapper = null; if (mbd.isSingleton ()) {instanceWrapper = this.factoryBeanInstanceCache.remove (beanName) } if (instanceWrapper = = null) {/ / delete some useless code. Here, reflection is called to create a bean, which is only an empty bean, and the attribute has not yet been assigned a value instanceWrapper = createBeanInstance (beanName, mbd, args);} final Object bean = (instanceWrapper! = null? InstanceWrapper.getWrappedInstance (): null); Object exposedObject = bean; try {/ / attribute assignment, and finally call reflection to assign populateBean (beanName, mbd, instanceWrapper); if (exposedObject! = null) {exposedObject = initializeBean (beanName, exposedObject, mbd);} return exposedObject } protected void populateBean (String beanName, RootBeanDefinition mbd, BeanWrapper bw) {/ / the pvs here is the PropertyValues pvs = mbd.getPropertyValues () injected into BeanDefinition when parsing the configuration file to get BeanDefinition; / / delete some code, and eventually you will call reflection assignment and jump around a bit complex applyPropertyValues (beanName, mbd, bw, pvs). } protected void addSingleton (String beanName, Object singletonObject) {/ / the bean will be saved after it is finally created (guess, after the Spring container is initialized, the non-lazily loaded bean has been saved in the Spring container in the following way, later through the @ Autowired annotation). It is obtained from this, just for analysis. Haven't seen the source code yet) synchronized (this.singletonObjects) {this.singletonObjects.put (beanName, (singletonObject! = null? SingletonObject: NULL_OBJECT); this.singletonFactories.remove (beanName); this.earlySingletonObjects.remove (beanName); this.registeredSingletons.add (beanName);}}
At this point, the study on "how to use Dubbo and Spring to integrate parsing configuration files" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 237
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.