dubbo2.x helloworld 消费者分析

本文使用上一篇写的dubbohello的基础上,对消费者的代码进行了基本分析。试图减少dubbo初学者对代码的疑惑。

消费者分析

  • 下面抄录dubbo hello world的的代码
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    package com.zw.dubbo;

    import com.zw.dubbo.service.DemoService;
    import org.springframework.context.support.ClassPathXmlApplicationContext;

    public class Consumer {

    public static void main(String[] args) {
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"classpath:consumer.xml"});
    context.start();
    DemoService demoService = (DemoService)context.getBean("demoService"); // 获取远程服务代理
    String hello = demoService.sayHello("你大爷"); // 执行远程方法
    System.out.println( hello ); // 显示调用结果
    }
    }
    从上面的代码可以看到,消费者的代码主要分成3部分:
  1. spring解析consumer.xml,把解析出来的bean对象初始化到spring容器中
  2. 从spring容器中拿出demoService的对象
  3. 调用spring的bean对象sayHello对象

看完上面的三个部分的代码,自然的就会有下面两个疑问:

  1. consumer.xml是如何被解析并依据解析结果创建spring bean对象的?
  2. spring的容器中这个demoService到底是什么对象,怎么实现的,调用sayHello方法的时候到是个什么样的过程?
  • 下面修改消费者代码:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    package com.zw.dubbo;

    import com.zw.dubbo.service.DemoService;
    import org.springframework.context.support.ClassPathXmlApplicationContext;

    public class Consumer {

    public static void main(String[] args) {
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"classpath:consumer.xml"});
    context.start();
    DemoService demoService = (DemoService)context.getBean("demoService"); // 获取远程服务代理
    System.out.println("demoService:" + demoService.getClass().toString());
    Object objectBean = context.getBean("&demoService");
    System.out.println("demoService bean:" + objectBean.getClass().toString());
    String hello = demoService.sayHello("你大爷"); // 执行远程方法
    System.out.println( hello ); // 显示调用结果
    }
    }
  • 再次运行代码返回结果:
    1
    2
    3
    demoService:class com.alibaba.dubbo.common.bytecode.proxy0
    demoService bean:class com.alibaba.dubbo.config.spring.ReferenceBean
    你大爷 hello, welcome to dubbo!
    至于为什么要用&demoService你需要了解一下Spring的FactoryBean相关的知识。
    从demoService:class com.alibaba.dubbo.common.bytecode.proxy0可以看出放到容器中的应该是个代理对象,结合demoService bean:class com.alibaba.dubbo.config.spring.ReferenceBean可以看出这个代理对象是com.alibaba.dubbo.config.spring.ReferenceBean这个类getObject方法生成的。
    如果要了解配置文件解析过程需要学习一些spring自定义xml配置标签