作为一个程序员小白,发现公司的项目中使用了Dubbo,于是闲暇之余学习了一下Dubbo的基础知识。
Dubbo的定义
百度上对Dubbo的定义是这样的:
Dubbo是阿巴巴公司开源的一个高性能优秀的服务框架,使得应用可通过高性能的 RPC
实现服务的输出和输入功能,可以和Spring框架无缝集成。Dubbo是一款高性能、轻量级的开源Java
RPC框架,它提供了三大核心能力:面向接口的远程方法调用,智能容错和负载均衡,以及服务自动注册和发现。
三大核心部件
Remoting
网络通信框架,实现了 sync-over-async 和request-response 消息机制。
RPC
一个远程过程调用的抽象,支持负载均衡、容灾和地址路由,动态配置等集群功能。
Registry
服务目录框架用于服务的注册和服务事件发布和订阅。
Spring集成
Dubbo采用全Spring配置方式,透明化接入应用,对应用没有任何API侵入,只需用Spring加载Dubbo的配置即可,Dubbo基于Spring的Schema扩展进行加载。
搭建第一个Dubbo服务
服务端
定义一个服务接口(HelloService.java)
package com.alibaba.hello.api;
public interface HelloService
{
String sayHelloWorld(String name);
}
接口实现类(HelloServiceImpl.java)
package com.alibaba.hello.impl;
import com.alibaba.hello.api.HelloService;
public class HelloServiceImpl implements HelloService{
public String sayHelloWorld(String name){
return"Hello"+ name;
}
}
Spring配置(provide.xml)
<?xmlversion="1.0"encoding="UTF-8"?>
<beans......>
<!--Applicationname-->
<dubbo:applicationname="hello-world-app"/>
<!--registryaddress,usedforservicetoregisteritself-->
<dubbo:registryaddress="multicast://127.0.0.1:1234"/>
<!--exposethisservicethroughdubboprotocol,throughport20880-->
<dubbo:protocolname="dubbo"port="20880"/>
<!--whichserviceinterfacedoweexpose?-->
<dubbo:serviceinterface="com.alibaba.hello.api.HelloService"ref="helloService"/>
<!--designateimplementation-->
<beanid="helloService"class="com.alibaba.hello.impl.HelloServiceImpl"/>
测试(Provider.java)
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Provider{
public static void main(String[] args){
ClassPathXmlApplicationContext context = newClassPathXmlApplicationContext(newString[]{"provider.xml"});
//启动成功,监听端口为20880
System.in.read();//按任意键退出
}
}
客户端
Spring配置文件(consumer.xml)
<?xmlversion="1.0"encoding="UTF-8"?>
<beansxmlns=......>
<!--consumerapplicationname-->
<dubbo:applicationname="consumer-of-helloworld-app"/>
<!--registryaddress,usedforconsumertodiscoverservices-->
<dubbo:registryaddress=" multicast://127.0.0.1:1234 "/>
<!--whichservicetoconsume?-->
<dubbo:referenceid="helloService"interface="com.alibaba.hello.api.HelloService"/>
客户端测试(Consumer.java)
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.alibaba.hello.api.HelloService;
public class Consumer{
public static void main(String[] args){
ClassPathXmlApplicationContext context = newClassPathXmlApplicationContext(newString[]{"consumer.xml"});
HelloService helloService = (HelloService)context.getBean("helloService");
}
}