本节笔记,主要参照手册《dubbo-user-book》,dubbo-io,以及蚂蚁课堂相关资料。
Dubbo需要:
- JDK: version 6 or higher
- Maven: version 3 or higher
Dubbo 采用全 Spring 配置方式,透明化接入应用,对应用没有任何 API 侵入,只需用Spring 加载 Dubbo 的配置即可,Dubbo 基于 Spring 的 Schema 扩展进行加载。服务端和客户端都需要引入dubbo的maven依赖,以及接口定义依赖
代码目录结构如下图:
定义接口API
将所有的接口,放置在mayi-start-api工程中, 然后在服务端,消费端添加接口定义的maven依赖。接口定义如下:
package xxx.dubbo.service;
public interface IOrderService {
/**
* 根据userId获取服务信息
* @param userId
* @return
*/
String getOrder(String userId);
}
服务端##
服务端需要添加dubbo的maven依赖,以及接口api的依赖,配置如下:
<!-- 接口api依赖 -->
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>mayi-start-api</artifactId>
<version>${project.version}</version>
</dependency>
<!-- 添加dubbo依赖 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>dubbo</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- 添加zk客户端依赖 -->
<dependency>
<groupId>com.github.sgroschupf</groupId>
<artifactId>zkclient</artifactId>
</dependency>
编写服务实现
package xxx.dubbo.service.impl;
import xxx.dubbo.service.IOrderService;
public class OrderServiceImpl implements IOrderService {
@Override
public String getOrder(String userId) {
return result+"你好";
}
}
暴露dubbo服务
<dubbo:application name="mayi-start-order-provider"/>
<dubbo:registry address="zookeeper://127.0.0.1:2181"/>
<dubbo:protocol name="dubbo" port="20890"/>
<dubbo:service interface="xxx.dubbo.service.IOrderService" ref="orderService"/>
<bean id="orderService" class="xxx.dubbo.service.impl.OrderServiceImpl"/>
</beans>
启动服务:
public class Provider {
public static void main(String[] args) throws IOException {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:provider.xml");
context.start();
System.out.println("provider启动注册成功");
System.in.read();//任意键退出
}
}
消费端##
消费端的依赖,参照服务端;
消费端的dubbo配置
<!-- 消费方应用名,用于计算依赖关系,不是匹配条件,不要与提供方一样 -->
<dubbo:application name="mayi-start-mben-consumer" />
<!-- 使用multicast广播注册中心暴露发现服务地址 -->
<dubbo:registry address="zookeeper://127.0.0.1:2181"/>
<!-- 生成远程服务代理,可以和本地bean一样使用demoService -->
<dubbo:reference id="orderService" interface="xxx.dubbo.service.IOrderService" />```
调用接口
调用接口,如同平时使用spring-bean一样
public class Consumer {
public static void main(String[] args) throws IOException {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:consumer.xml");
context.start();
System.out.println("consumer启动成功");
IOrderService orderService = (IOrderService) context.getBean("orderService");
String result = orderService.getOrder("1");
System.out.println("result="+result);
System.in.read();//任意键退出
}
}