1.创建dubbo-demo-consumer并添加依赖
<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>
2.新建配置文件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一样使用 check属性,启动时候是否检查 一般设置成false 启动时候不检查 -->
<dubbo:reference id="demoProviderService" check="false" interface="com.java1234.service.DemoProviderService"/>
</beans>
3.同样的也需要创建调用接口
package com.java1234.service;
/**
* 服务提供者接口
* @author Administrator
*
*/
public interface DemoProviderService {
public String sayHello(String name);
}
4.编写服务消费者启动类
import java.io.IOException;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.java1234.service.DemoProviderService;
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();
}
}