(五)消费Dubbo服务

时间:2021-02-10 22:47:11

前面我们搞了发布Dubbo服务,发布的服务就是用来消费的,所以我们这里来调用服务,消费下;

创建maven项目 dubbo-demo-consumer

pom.xml配置下:

 <dependencies>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>dubbo</artifactId>
<version>2.6.0</version>
</dependency>
<dependency>
<groupId>com.101tec</groupId>
<artifactId>zkclient</artifactId>
<version>0.10</version>
</dependency>
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-framework</artifactId>
<version>4.0.1</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.46</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.25</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.4</version>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.0.35.Final</version>
</dependency>
</dependencies>

再搞个dubbo-demo-consumer.xml

 <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd"> <!-- 消费方应用名,用于计算依赖关系,不是匹配条件,不要与提供方一样 -->
<dubbo:application name="demo-consumer"/> <!-- 使用zookeeper注册中心暴露服务地址 -->
<dubbo:registry address="zookeeper://127.0.0.1:2181"/> <!-- 生成远程服务代理,可以和本地bean一样使用demoProviderService check属性,启动的时候是否检查 一般设置为false 启动的时候不检查-->
<dubbo:reference id="demoProviderService" check="false" interface="com.wishwzp.service.DemoProviderService"/> </beans>

创建接口DemoProviderService.java

 package com.wishwzp.service;

 /**
* 服务提供者接口
* @author Administrator
*
*/
public interface DemoProviderService { public String sayHello(String name);
}

搞个测试类ConsumerTest:

 import com.wishwzp.service.DemoProviderService;
import org.springframework.context.support.ClassPathXmlApplicationContext; import java.io.IOException; public class ConsumerTest { public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"dubbo-demo-consumer.xml"});
context.start();
DemoProviderService demoProviderService=(DemoProviderService) context.getBean("demoProviderService");
String result=demoProviderService.sayHello("你好");
System.out.println("远程调用结果:"+result);
try {
System.in.read();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
context.close();
}
}

运行结果 远程调用结果:服务001

说明远程调用成功;