dubbo 原理和入门实践
一。dubbo:
远程服务调用的分布式框架
其核心部分包含:
1. 远程通讯: 提供对多种基于长连接的NIO框架抽象封装,包括多种线程模型,序列化,以及“请求-响应”模式的信息交换方式。
2. 集群容错: 提供基于接口方法的透明远程过程调用,包括多协议支持,以及软负载均衡,失败容错,地址路由,动态配置等集群支持。
3. 自动发现: 基于注册中心目录服务,使服务消费方能动态的查找服务提供方,使地址透明,使服务提供方可以平滑增加或减少机器
二。dubbo 框架架构图
2.1 流程分析
0 服务容器负责启动,加载,运行服务提供者。
3. 注册中心返回服务提供者地址列表给消费者,如果有变更,注册中心将基于长连接推送变更数据给消费者。
4. 服务消费者,从提供者地址列表中,基于软负载均衡算法,选一台提供者进行调用,如果调用失败,再选另一台调用。
5. 服务消费者和提供者,在内存中累计调用次数和调用时间,定时每分钟发送一次统计数据到监控中心。
三。相关代码和demo 实现步骤
3.1 官网代码demo说明
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"META-INF/spring/dubbo-demo-provider.xml"});
context.start();
System.in.read(); // press any key to exit
程序启动读取对应的resouce 下的xml 文件,
声明一个接口和服务,
public interface DemoService {
String sayHello(String name);
}
声明接口的实现类:
public class DemoServiceImpl implements DemoService {
@Override
public String sayHello(String name) {
System.out.println("[" + new SimpleDateFormat("HH:mm:ss").format(new Date()) + "] Hello " + name + ", request from consumer: " + RpcContext.getContext().getRemoteAddress());
return "Hello " + name + ", response from provider: " + RpcContext.getContext().getLocalAddress();
}
}
接口中的方法主要是通过字符串从服务器获取相应的字符串。
这里是一个demo Service 实现,需要在dobbu 中配置相应的配置文件,
<!-- service implementation, as same as regular local bean -->
<bean id="demoService" class="org.apache.dubbo.demo.provider.DemoServiceImpl"/>
<!-- declare the service interface to be exported -->
<dubbo:service interface="org.apache.dubbo.demo.DemoService" ref="demoService"/>
<dubbo:registry address="multicast://224.5.6.7:1234"/>
<!-- use dubbo protocol to export service on port 20880 -->
<dubbo:protocol name="dubbo" port="20880"/>
通过注册dubbo 协议服务和多播实现。
在服务器端中实现:
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"META-INF/spring/dubbo-demo-consumer.xml"});
context.start();
DemoService demoService = (DemoService) context.getBean("demoService"); // get remote service proxy
在加载类路径下的*spring.xml 文件的
通过对注册的multicast 实现引用接口下的服务demoServer. 调用接口中的发布的service 的方法。
DemoService demoService = (DemoService) context.getBean("demoService"); // get remote service proxy
String hello = demoService.sayHello("world"); // call remote method
调用远程代理和远程方法。
3.2 注册到zookeeper 的实现
下载api代码,并install 供privider和customer 使用。
启动prider 代码,修改zk 地址。
启动customer 代码:
结果如下:
四。参考资料:
官方文档:
https://github.com/apache/incubator-dubbo/tree/2.5.x
管理控制台:
https://www.cnblogs.com/xhj123/p/8975840.html
https://www.cnblogs.com/leemz-coding/p/7113530.html
https://blog.****.net/houshaolin/article/details/76408399
五.附件代码:
入门demo:https://github.com/apache/incubator-dubbo/tree/2.5.x/dubbo-demo