至于为什么要用maven多模块构建项目,和dubbo是做什么的就不多说了,直接开始。
首先创建一个maven项目作为root模块 命名为mydubbo,并删除其中的src目录(不需要)
除外我们需要Spring,zookeeper的依赖
mydubbo->pom.xml
4.0.0
com
mydubbo
pom
1.0-SNAPSHOT
3.2.4.RELEASE
myProvider
myConsumer
myService
com.alibaba
dubbo
2.5.3
org.springframework
spring
org.apache.zookeeper
zookeeper
3.4.6
com.github.sgroschupf
zkclient
0.1
org.springframework
spring-core
${spring.version}
org.springframework
spring-context
${spring.version}
然后创建三个maven子模块分别为myService、myProvider、myConsumer
myService:功能接口模块
myProvider:dubbo提供者
myConsumer:dubbo消费者
因为消费者和提供者的功能接口一致,所以都依赖myService模块(myService的项目packing 为 jar)
myProvider->pom.xml
mydubbo
com
1.0-SNAPSHOT
4.0.0
myProvider
com
myService
1.0-SNAPSHOT
mydubbo
com
1.0-SNAPSHOT
4.0.0
myConsumer
com
myService
1.0-SNAPSHOT
mydubbo
com
1.0-SNAPSHOT
4.0.0
myService
myService
jar
HelloService.java
package com.service;
/**
* Created by yuyufeng on 2016/11/16.
*/
public interface HelloService {
String speakHello(String name);
}
myProvider的依赖就有myService产生的jar
现在,开始编写dubbo提供者myProvider的代码
首先,需要提供HelloService的实现
HelloServiceImpl.java
package com.service.impl;
import com.service.HelloService;
/**
* Created by yuyufeng on 2016/11/16.
*/
public class HelloServiceImpl implements HelloService {
public String speakHello(String name) {
return "你好:" + name;
}
}
然后使
用Spring配置声明暴露服务,建立一个provider.xml 如下
package com.service.impl;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.io.IOException;
/**
* Created by yuyufeng on 2016/11/16.
*/
public class ProviderServer{
public static void main(String[] args) throws IOException {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("provider.xml");
context.start();
//按任意键退出
System.in.read();
}
}
然后,就编写个消费者通过dubbo来调以下远程的服务吧
消费者通过Spring配置引用远程服务spring配置文件如下:
consumer.xml
消费者启动类
ConsumerClient.java
import com.service.HelloService;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* Created by yuyufeng on 2016/11/16.
*/
public class ConsumerClient {
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("consumer.xml");
HelloService helloService = (HelloService) context.getBean("helloService");
String result = helloService.speakHello("yyf");
System.out.println(result);
}
}
运行改类,结果如下:
可以看到,远程服务调用成功。