一.为何使用dubbo
使用dubbo。使用rpc协议进行远程调用,之间使用socket通信,传输效率高,并且可以统计出系统之间的调用关系、调用次数。
说白了dubbo就是一个服务治理工具,是一个服务的中间件,由于dubbo是通过java编写的,dubbo最大的缺点就出现了,它只适用于java系统间的通信。
二.bubbo的架构
角色说明
Provider:暴露服务的服务提供方
Container:服务运行容器
Consumer:调用服务的消费方
Registry:注册服务与发现服务中心
Monitor:统计服务调用的监控中心(可有可无)
调用关系说明
0:服务运行容器启动,加载服务提供者
1:在启动时告诉注册中心服务方有什么服务
2:消费者调用服务时,先到注册中心订阅所需要服务
3:注册中心返回结果即该服务的地址
4:消费者通过地址调用服务(此时注册中心没用了)
5:服务消费者和提供者,在内存中累计调用次数和调用时间,定时每分钟发送一次到监控中心
三.如何使用
Dubbo使用Spring配置方式,只需用Spring加载Dubbo的配置即可。
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:dubbo="http://code.alibabatech.com/schema/dubbo" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.2.xsd"> <!-- 配置包扫描器,扫描所有带@Service注解的类 --> <context:component-scan base-package="xxxx.service"/> <!-- 发布dubbo服务 --> <!-- 提供方应用信息,用于计算依赖关系 --> <dubbo:application name="xxxx" /> <!-- 注册中心的地址 --> <dubbo:registry protocol="zookeeper" address="192.168.224.50:2181" /> <!-- 用dubbo协议在20880端口暴露服务 --> <dubbo:protocol name="dubbo" port="20880" /> <!-- 声明需要暴露的服务接口 --> <dubbo:service interface="xxxx.ItemService" ref="itemServiceImpl" timeout="300000"/> <dubbo:service interface="xxxx.ItemCatService" ref="itemCatServiceImpl" timeout="300000"/> </beans>
到此,dubbo提供方该做的都做了,剩下的工作就是消费方的事情,他们如何调用的问题了
四.消费方如何调用
首先引入Dubbo的dtd文件头,上述配置文件为服务提供者,通过zookeeper暴露服务,timeout=“300000”为debug调试时候使用。下面则是消费者引用dubbo服务。
<!-- 引用dubbo服务 --> <dubbo:application name="xxxx"/> <dubbo:registry protocol="zookeeper" address="192.192.255.50:8080" /> <dubbo:reference interface="xxxx.ItemService" id="itemService" />