Dubbo 是阿里开源的一套服务治理框架,在众多互联网企业里应用广泛。当当在dubbo的基础上开发了 dubbox (Dubbo eXtensions),支持REST风格远程调用。
Dubbo本身的维护已经不太活跃了,最新的版本是 2.5.4-SNAPSHOT 。当当接下了维护的重任,目前的最新版是 dubbox-2.8.4 ,其实groupId和artifactId还是原来的不变,只是版本号有变化罢了。
本文将分两章节写,第一章节构建dubbo服务,第二章节将dubbo服务改造为rest service,这样就可以方便的知道做了哪些改造。
一、搭建dubbo服务
Dubbo本身的维护已经不太活跃了,最新的版本是 2.5.4-SNAPSHOT 。当当接下了维护的重任,目前的最新版是 dubbox-2.8.4 ,其实groupId和artifactId还是原来的不变,只是版本号有变化罢了。
本文将分两章节写,第一章节构建dubbo服务,第二章节将dubbo服务改造为rest service,这样就可以方便的知道做了哪些改造。
一、搭建dubbo服务
1. 新建maven项目,引入依赖
<!-- spring framework -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>3.2.9.RELEASE</version>
</dependency>
<!-- dubbo -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>dubbo</artifactId>
<version>2.4.9</version>
</dependency>
<!-- zokeeper register center -->
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>3.3.3</version>
</dependency>
<dependency>
<groupId>com.github.sgroschupf</groupId>
<artifactId>zkclient</artifactId>
<version>0.1</version>
</dependency>
2. 新建服务与实现
public interface DemoService {
String sayHello(String name);
}
public class DemoServiceImpl implements DemoService {
public String sayHello(String name) {
return "Hello " + name;
}
}
3. 在src/main/resources资源目录下添加provider.xml 和consumer.xml配置文件
1. provider.xml用于配置dubbo服务相关信息,包括服务名称、祖册中心和暴露服务
<!-- 提供方应用信息,用于计算依赖关系 -->
<dubbo:application name="dubbo-test-service" />
<!-- 使用zookpeeper注册中心暴露服务地址 -->
<dubbo:registry address="zookeeper://127.0.0.1:2181" client="zkclient" />
<!-- 用dubbo协议在20880端口暴露服务 -->
<dubbo:protocol name="dubbo" port="20880" />
<!-- 声明需要暴露的服务接口 -->
<dubbo:service interface="net.xiaocun.DemoService" ref="demoService" />
<!-- 和本地bean一样实现服务 -->
<bean id="demoService" class="net.xiaocun.impl.DemoServiceImpl" />
2.consumer.xml用于配置服务调用所需信息
<!-- 消费方应用名,用于计算依赖关系,不是匹配条件,不要与提供方一样 -->
<dubbo:application name="dubbo-test-consumer" />
<!-- 使用zookpeer注册中心暴露发现服务地址 -->
<dubbo:registry address="zookeeper://127.0.0.1:2181" />
<!-- 生成远程服务代理,可以和本地bean一样使用demoService -->
<dubbo:reference id="demoService" interface="net.xiaocun.DemoService" />
4. 调用服务测试
1. 新建Provider.java,用于启动服务
public static void main(String[] args) throws Exception {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"provider.xml"});
context.start();
System.out.println("请按任意键退出");
System.in.read(); // 按任意键退出
}
2.新建Consumer.java,调用dubbo服务,和本地调用一样。
public static void main(String[] args) throws Exception {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"consumer.xml"});
context.start();
DemoService demoService = (DemoService)context.getBean("demoService"); // 获取远程服务代理
String res = demoService.sayHello("world"); // 执行远程方法
System.out.println( res ); // 显示调用结果
}
二、关于利用dubbox改造,对外提供rest服务,请参照第二章节