基于Dubbo协议的消费者示例及详解(三)

来源:互联网 发布:linux下安装qt creator 编辑:程序博客网 时间:2024/05/13 22:58

接下来就剩下消费者的模块了,消费者模块跟提供者类似,创建maven项目、引入接口DubboInterface.jar包、增加Spring依赖、Dubbo依赖。

1、spring.xml配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:p="http://www.springframework.org/schema/p"
xmlns:jee="http://www.springframework.org/schema/jee" 
xsi:schemaLocation="http://www.springframework.org/schema/beans   
http://www.springframework.org/schema/beans/spring-beans.xsd   
http://www.springframework.org/schema/context   
http://www.springframework.org/schema/context/spring-context-3.2.xsd   
http://code.alibabatech.com/schema/dubbo     
http://code.alibabatech.com/schema/dubbo/dubbo.xsd  
http://www.springframework.org/schema/aop   
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd   
http://www.springframework.org/schema/jee   
http://www.springframework.org/schema/jee/spring-jee-3.2.xsd 
http://www.springframework.org/schema/tx   
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">

   <!-- 消费方应用信息 -->
    <dubbo:application name="dubboconsumer"></dubbo:application>
    
    <!-- 到zookeepeer获取服务 -->
    <dubbo:registry address="zookeeper://127.0.0.1:2181"/>
    <!-- 消费方用什么协议获取服务(用dubbo协议在20880端口获取服务) -->
    <dubbo:protocol accesslog="/data/logs/access.log"  name="dubbo" server="netty" host="127.0.0.1" port="20880" />

<!-- 声明需要获取的服务接口 这里是reference,提供者是service-->
<dubbo:reference id="sayHello" interface="com.song.demo.DubboInterface.ISayHelloInterface" protocol="dubbo"version="1.0.0"/>

</beans>


2、模拟测试类ConsumerTest,用于模拟发起请求

package com.song.demo.DubboConsumer;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.song.demo.DubboInterface.ISayHelloInterface;

public class ConsumerTest {

public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml");
ISayHelloInterface sayHello = (ISayHelloInterface)ctx.getBean("sayHello");//获取spring.xml配置的bean

System.out.println("Consumer 调用sayHello服务:");
System.out.println("提供者返回结果:"+sayHello.sayHello("testUser"));//调用方法
}
}

右键运行后,控制台打印效果如下:


0 0
原创粉丝点击