前言
本章讲解dubbo中另外一个重要角色Consumer的编写
方法
1.概念
既然我们在上个章节创建了dubbo的服务提供者provider,那么必然是要有消费者进行消费的。
本章将根据dubbo流程图进一步探寻。
consumer可以是java工程也可以是web工程,本次使用java工程进行讲解。
2.编写步骤
1)新建maven的jar工程
2)编写pom.xml
实际上,该pom文件的内容和provider一模一样。
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>cn.edu.ccut</groupId>
<artifactId>dubbo-consumer</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<!-- 引入接口项目依赖,必须 -->
<dependency>
<groupId>cn.edu.ccut</groupId>
<artifactId>dubbo-service</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
<!-- 引入Dubbo相关jar坐标 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>dubbo</artifactId>
<version>2.6.5</version>
</dependency>
<!-- 引入zookeeper框架Curator相关jar坐标 -->
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-framework</artifactId>
<version>4.1.0</version>
<exclusions>
<exclusion>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>3.4.9</version>
</dependency>
</dependencies>
</project>
3)编写dubbo相关的配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:dubbo="http://dubbo.apache.org/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-4.3.xsd
http://dubbo.apache.org/schema/dubbo http://dubbo.apache.org/schema/dubbo/dubbo.xsd">
<!-- consumer的名字 -->
<dubbo:application name="demo-consumer"/>
<!-- dubbo所使用的注册中心 protocol表示是什么注册中心,address代表注册中心ip+端口号 -->
<dubbo:registry address="192.168.1.106:2181" protocol="zookeeper"/>
<!-- 调用对外提供的service接口 -->
<dubbo:reference id="demoService" interface="cn.edu.ccut.dubbo.DemoService"/>
</beans>
4)加载Spring配置,并调用远程服务
package cn.edu.ccut.dubbo;
import java.io.IOException;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) throws IOException {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
new String[]{"applicationContext-dubbo.xml"});
//调用接口方法
DemoService demoService = context.getBean("demoService",DemoService.class);
System.out.println(demoService.getString("啦啦啦"));
}
}
5)运行Test类,观察效果
注意:必须保证Provider端正常开启