Dubbo笔记

Dubbo笔记

本文是对Dubbo2.7版本作的笔记
学习Dubbo建议多看官方文档,因为文档是中文的。

一、Dubbo架构

1. Dubbo架构概述

1.1 什么是Dubbo

Apache Dubbo 是一款高性能、轻量级的开源服务框架即Java RPC框架。其前身是阿里巴巴公司开源的框架,后来贡献给了Apache,可以和Spring框架无缝集成。

1.2 Dubbo的特性

提供了六大核心能力:

  • 面向接口代理的高性能RPC调用
  • 智能容错和负载均衡
  • 服务自动注册和发现
  • 高度可扩展能力
  • 运行期流量调度
  • 可视化的服务治理与运维
    详情见官网:https://dubbo.apache.org/zh/#td-block-1

2 Dubbo架构

见这里
https://dubbo.apache.org/zh/docsv2.7/user/preface/architecture/

3 服务注册中心Zookeeper

二、Dubbo实战

1. 开发Dubbo Demo

1.1 创建demo-base项目

pom.xml文件引入dubbo的依赖为

<dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>com.mh.study.dubbo</groupId>
                <artifactId>service-api</artifactId>
                <version>${project.version}</version>
            </dependency>
            <dependency>
                <groupId>org.apache.dubbo</groupId>
                <artifactId>dubbo</artifactId>
                <version>${dubbo.version}</version>
            </dependency>
            <dependency>
                <groupId>org.apache.dubbo</groupId>
                <artifactId>dubbo-common</artifactId>
                <version>${dubbo.version}</version>
            </dependency>
            <dependency>
                <groupId>org.apache.dubbo</groupId>
                <artifactId>dubbo-registry-zookeeper</artifactId>
                <version>${dubbo.version}</version>
            </dependency>
            <dependency>
                <groupId>org.apache.dubbo</groupId>
                <artifactId>dubbo-registry-nacos</artifactId>
                <version>${dubbo.version}</version>
            </dependency>
            <dependency>
                <groupId>org.apache.dubbo</groupId>
                <artifactId>dubbo-rpc-dubbo</artifactId>
                <version>${dubbo.version}</version>
            </dependency>
            <dependency>
                <groupId>org.apache.dubbo</groupId>
                <artifactId>dubbo-remoting-netty4</artifactId>
                <version>${dubbo.version}</version>
            </dependency>
            <dependency>
                <groupId>org.apache.dubbo</groupId>
                <artifactId>dubbo-serialization-hessian2</artifactId>
                <version>${dubbo.version}</version>
            </dependency>
        </dependencies>
    </dependencyManagement>
1.2 创建service-api子项目
创建接口

com.mh.study.dubbo.service.HelloService

package com.mh.study.dubbo.service;

public interface HelloService {
    String sayHello(String name);
}

1.3 创建service-provider子项目
创建dubbo-provider.properties
dubbo.application.name=service-provider
dubbo.protocol.name=dubbo
dubbo.protocol.port=20880
创建实现类

com.mh.study.dubbo.service.impl.HelloServiceImpl
注意这里的@Service是dubbo的不是spring的

package com.mh.study.dubbo.service.impl;

import com.mh.study.dubbo.service.HelloService;
import org.apache.dubbo.config.annotation.Service;

@Service
public class HelloServiceImpl implements HelloService {
    @Override
    public String sayHello(String name) {
        return "Hello " + name;
    }
}
创建启动类

com.mh.study.dubbo.DubboPureMain

public class DubboPureMain {
    public static void main(String[] args) throws IOException {
        AnnotationConfigApplicationContext applicationContext =
                new AnnotationConfigApplicationContext(ProviderConfiguration.class);
        applicationContext.start();
        System.in.read();
    }

    @Configuration
    @EnableDubbo(scanBasePackages = "com.mh.study.dubbo.service.impl")
    @PropertySource("classpath:/dubbo-provider.properties")
    static class ProviderConfiguration {

        @Bean
        public RegistryConfig registryConfig() {
            RegistryConfig registryConfig = new RegistryConfig();
            registryConfig.setAddress("zookeeper://127.0.0.1:2181");
            return registryConfig;
        }

    }
}
1.4 创建service-consumer子项目
创建dubbo-consumer.properties
dubbo.application.name=service-provider
dubbo.protocol.name=dubbo
dubbo.protocol.port=20880
创建调用者

com.mh.study.dubbo.component.HelloComponent

package com.mh.study.dubbo.component;

import com.mh.study.dubbo.service.HelloService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Component;

@Component
public class HelloComponent {

    @Reference
    private HelloService helloService;

    public String sayHello(String name){
        return helloService.sayHello(name);
    }

}
创建启动类

com.mh.study.dubbo.ServiceConsumerMain

public class ServiceConsumerMain {

    public static void main(String[] args) throws IOException {
        System.out.println("-------------");
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ConsumerConfiguration.class);
        context.start();
        // 获取消费者组件
        HelloComponent service = context.getBean(HelloComponent.class);
        while (true) {
            System.out.println("请输入回车");
            System.in.read();
            String hello = service.sayHello("world");
            System.out.println("result:" + hello);
        }
    }

    @Configuration
    @ComponentScan("com.mh.study.dubbo.component")
    @EnableDubbo(scanBasePackages = "com.mh.study.dubbo.service")
    @PropertySource("classpath:/dubbo-consumer.properties")
    static class ConsumerConfiguration {
    }
}

2. XML方式

与上面的引入的pom相同,删除配置类,及@Service和@Reference注解

2.1 service-provider子项目
创建dubbo-provider.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:dubbo="http://dubbo.apache.org/schema/dubbo"
       xmlns="http://www.springframework.org/schema/beans"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
       http://dubbo.apache.org/schema/dubbo
       http://dubbo.apache.org/schema/dubbo/dubbo.xsd">

    <dubbo:application name="dubbo-provider"/>
    <dubbo:registry address="zookeeper://127.0.0.1:2181"/>
    <dubbo:protocol name="dubbo"/>
    <bean id="helloService" class="com.mh.study.dubbo.service.impl.HelloServiceImpl"/>
    <dubbo:service interface="com.mh.study.dubbo.service.HelloService" ref="helloService"/>
</beans>
修改启动类为
public class DubboPureMain {

    public static void main(String[] args) throws IOException {
        ClassPathXmlApplicationContext applicationContext =
                new ClassPathXmlApplicationContext("classpath:dubbo-provider.xml");
        applicationContext.start();
        System.out.println("xml方式启动完成-----------");
        System.in.read();
    }

}
2.2 service-consumer子项目
创建dubbo-consumer.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:dubbo="http://dubbo.apache.org/schema/dubbo"
       xmlns="http://www.springframework.org/schema/beans"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
       http://dubbo.apache.org/schema/dubbo
       http://dubbo.apache.org/schema/dubbo/dubbo.xsd">

    <dubbo:application name="dubbo-consumer"/>
    <dubbo:registry address="zookeeper://127.0.0.1:2181"/>
    <dubbo:reference id="helloService" interface="com.mh.study.dubbo.service.HelloService"/>
    <bean id="helloComponent" class="com.mh.study.dubbo.component.HelloComponent">
        <property name="helloService" ref="helloService" />
    </bean>

</beans>
修改启动类为
public class ServiceConsumerMain {

    public static void main(String[] args) throws IOException {
        System.out.println("-------------");
        ClassPathXmlApplicationContext applicationContext =
                new ClassPathXmlApplicationContext("classpath:dubbo-consumer.xml");
        applicationContext.start();
        // 获取消费者组件
        HelloComponent service = applicationContext.getBean(HelloComponent.class);
        while (true) {
            System.out.println("xml方式,请输入回车");
            System.in.read();
            String hello = service.sayHello("world");
            System.out.println("result:" + hello);
        }
    }

}

3. 配置方式介绍

  1. 注解: 基于注解可以快速的将程序配置,无需多余的配置信息,包含提供者和消费者。但是这种方式有一个弊端,有些时候配置信息并不是特别好找,无法快速定位。
  2. XML: 一般这种方式我们会和Spring做结合,相关的Service和Reference均使用Spring集成后的。
    通过这样的方式可以很方便的通过几个文件进行管理整个集群配置。可以快速定位也可以快速更改。
    现在大部分框架流行于注解的方式

4. Dubbo管理控制台 dubbo-admin

4.1 安装
  1. 下载代码: git clone https://github.com/apache/dubbo-admin.git
  2. 在dubbo-admin-server/src/main/resources/application.properties中指定注册中心地址
  3. 构建
    • mvn clean package -Dmaven.test.skip=true
  4. 启动
    • mvn --projects dubbo-admin-server spring-boot:run 或者
    • cd dubbo-admin-distribution/target; java -jar dubbo-admin-0.1.jar
  5. 访问 http://localhost:8080
4.2 Swagger 支持

部署完成后,可以访问 http://localhost:8080/swagger-ui.html 来查看所有的restful api

5. Dubbo配置项说明

dubbo:application

对应 org.apache.dubbo.config.ApplicationConfig, 代表当前应用的信息

  1. name 当前应用程序的名称,在dubbo-admin中会以此名称表示这个应用。
  2. owner 当前应用程序的责任人,可以通过这个负责人找到期相应的应用列表,用于快速定位到责任人;
  3. qosEnable 是否启动QOS 默认true启动;
  4. qosPort QOS的端口 默认22222;
  5. qosAcceptForeignIp: 是否允许远程访问,默认false;
dubbo:registry

对应 org.apache.dubbo.config.RegistryConfig, 代表该模块所使用的注册中心。一个模块中的服务可以将其注册到多个注册中心上,也可以注册到一个上。后面再service和reference也会引入这个注册中心。

属性说明
id当前服务中provider或者consumer中存在多个注册中心时,则使用需要增加该配置,在一些公司,会通过业务线的不同选择不同的注册中心,所以一般都会配置该值。
address当前注册中心的访问地址。
protocol当前注册中心所使用的协议是什么。也可以直接在address 中写入,比如使用zookeeper,就可以写成zookeeper://xx.xx.xx.xx:2181
timeout当与注册中心不再同一个机房时,大多会把该参数延长。
dubbo:protocol

对应:org.apache.dubbo.config.ProtocolConfig, 指定服务在进行数据传输所使用的协议。

属性说明
id在大公司,可能因为各个部门技术栈不同,所以可能会选择使用不同的协议进行交互。这里在多个协议使用时,需要指定。
name指定协议名称,默认使用dubbo。
dubbo:service

对应org.apache.dubbo.config.ServiceConfig, 用于指定当前需要对外暴露的服务信息。

属性说明
interface指定当前需要进行对外暴露的接口是什么。
ref具体实现对象的引用,一般我们在生产级别都是使用Spring去进行Bean托管的,所以这里面一般也指的是Spring中的BeanId。
version对外暴露的版本号。不同的版本号,消费者在消费的时候只会根据固定的版本号进行消费。
dubbo:reference

对应org.apache.dubbo.config.ReferenceConfig, 消费者的配置

属性说明
id指定该Bean在注册到Spring中的id
interface服务接口名
version指定当前服务版本,与服务提供者的版本一致。
registry指定所具体使用的注册中心地址。这里面也就是使用上面在dubbo:registry 中所声明的id。
dubbo:method

对应org.apache.dubbo.config.MethodConfig,用于在制定的dubbo:service 或者dubbo:reference 中的更具体一个层级,指定具体方法级别在进行RPC操作时候的配置,可以理解为对这上面层级中的配置针对于具体方法的特殊处理。

属性说明
name指定方法名称,用于对这个方法名称的RPC调用进行特殊配置
async是否异步 默认false
dubbo:service和dubbo:reference详解

这两个在dubbo中是我们最为常用的部分,其中有一些我们必然会接触到的属性。并且这里会列举到一些设置上的使用方案。

属性说明
mock用于在方法调用出现错误时,当做服务降级来统一对外返回结果
timeout用于指定当前方法或者接口中所有方法的超时时间。我们一般都会根据提供者的时长来具体规定。比如我们在进行第三方服务依赖时可能会对接口的时长做放宽,防止第三方服务不稳定导致服务受损。
check用于在启动时,检查生产者是否有该服务。我们一般都会将这个值设置为false,不让其进行检查。因为如果出现模块之间循环引用的话,那么则可能会出现相互依赖,都进行check的话,那么这两个服务永远也启动不起来。
retries用于指定当前服务在执行时出现错误或者超时时的重试机制
executes用于在提供者做配置,来确保最大的并行度。

retries需要注意以下几点

  1. 注意提供者是否有幂等,否则可能出现数据一致性问题
  2. 注意提供者是否有类似缓存机制,如出现大面积错误时,可能因为不停重试导致雪崩

executes需要注意以下几点

  1. 可能导致集群功能无法充分利用或者堵塞

  2. 但是也可以启动部分对应用的保护功能

  3. 可以不做配置,结合后面的熔断限流使用

三、Dubbo高级实战

1. SPI

1.1 SPI简介

  SPI全称为(Service Provicer Interface),是JDK内置的一种服务提供发现机制。目前有不少框架用它来做服务的扩展发现,简单来说,它就是一种动态替换发现的机制。使用SPI机制的优势是实现解耦,使得第三方服务模块的装配控制逻辑与调用者的业务代码分离。

1.2 JDK中的SPI

  Java中如果想要使用SPI功能,先提供标准服务接口,然后再提供相关接口实现和调用者。这样就可以通 过SPI机制中约定好的信息进行查询相应的接口实现。

SPI遵循如下约定:
1、当服务提供者提供了接口的一种具体实现后,在META-INF/services目录下创建一个以“接口全限定名”为命名的文件,内容为实现类的全限定名;
2、接口实现类所在的jar包放在主程序的classpath中;
3、主程序通过java.util.ServiceLoader动态装载实现模块,它通过扫描META-INF/services目录下的配置文件找到实现类的全限定名,把类加载到JVM;
4、SPI的实现类必须携带一个无参构造方法;

demo详见java-spi-demo

1.3 Dubbo中的SPI

  dubbo中大量的使用了SPI来作为扩展点,通过实现同一接口的前提下,可以进行定制自己的实现类。比如比较常见的协议,负载均衡,都可以通过SPI的方式进行定制化,自己扩展。Dubbo中已经存在的所有已经实现好的扩展点。
详细介绍见官网介绍扩展Dubbo
demo详见dubbo-spi-demo

在这里插入图片描述

1.4 Dubbo SPI中的Adaptive功能

  Dubbo中的Adaptive功能,主要解决的问题是如何动态的选择具体的扩展点。通过getAdaptiveExtension 统一对指定接口对应的所有扩展点进行封装,通过URL的方式对扩展点来进行动态选择。 (dubbo中所有的注册信息都是通过URL的形式进行处理的。)这里同样采用相同的方式进行实现。

demo详见dubbo-spi-demo

创建接口类

@SPI("human")
public interface HelloService {
    @Adaptive
    String  sayHello(URL url);
}

创建实现类

public class HumanHelloServiceImpl implements HelloService {
    @Override
    public String sayHello(URL url) {
        return "Hello url";
    }
}

创建Main

public class DubboAdaptiveMain {
    public static void main(String[] args) {
        URL url = URL.valueOf("test://localhost/hello?hello.service=human");
        HelloService adaptiveExtension = ExtensionLoader.getExtensionLoader(HelloService.class).getAdaptiveExtension();
        String  msg = adaptiveExtension.sayHello(url);
        System.out.println(msg);
    }
}

关于URL参数:

  • 因为在这里只是临时测试,所以为了保证URL规范,前面的信息均为测试值即可。
  • 关键的点在于hello.service 参数,这个参数的值指定的就是具体的实现方式。关于为什么叫hello.service 是因为这个接口的名称,其中后面的大写部分被dubbo自动转码为 . 分割。
  • 通过getAdaptiveExtension 来提供一个统一的类来对所有的扩展点提供支持(底层对所有的扩展点进行封装)。
  • 调用时通过参数中增加URL 对象来实现动态的扩展点使用。
  • 如果URL没有提供该参数,则该方法会使用默认在SPI注解中声明的实现。
1.5 Dubbo调用时拦截操作

  Dubbo的Filter机制,是专门为服务提供方和服务消费方调用过程进行拦截设计的,每次远程方法执行,该拦截都会被执行。这样就为开发者提供了非常方便的扩展性,比如为dubbo接口实现ip白名单功能、监控功能 、日志记录等。

demo详见demo-base-filter

实现org.apache.dubbo.rpc.Filter接口

@Activate(group = {CommonConstants.PROVIDER, CommonConstants.CONSUMER})
public class HelloFilter implements Filter {
    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        long startTime = System.currentTimeMillis();
        try {
            // 执行方法
            return invoker.invoke(invocation);
        } finally {
            System.out.println("invoke time:" + (System.currentTimeMillis() - startTime) + "毫秒");
        }

@Activate注解的group指定提供端、消费端
在META-INF.dubbo中新建org.apache.dubbo.rpc.Filter文件,并将当前类的全名写入

timerFilter=com.mh.study.dubbo.filter.HelloFilter

注意:一般类似于这样的功能都是单独开发依赖的,所以再使用方的项目中只需要引入依赖,在调用接口时,该方法便会自动拦截。

2. 负载均衡策略

  在集群负载均衡时,Dubbo 提供了多种均衡策略,缺省为 random 随机调用。
  具体实现上,Dubbo 提供的是客户端负载均衡,即由 Consumer 通过负载均衡算法得出需要将请求提交到哪个 Provider 实例。
详细介绍见官网介绍Dubbo负载均衡

2.1 负载均衡基本配置

提供方配置

//在服务提供者一方配置负载均衡
@Service(loadbalance = "random")
public class HelloServiceImpl implements HelloService {
    public String sayHello(String name) {
        return "hello " + name;
    }
}

消费方配置

//在服务消费者一方配置负载均衡策略
@Reference(check = false,loadbalance = "random")
//
2.2 自定义负载均衡器

负载均衡器也是基于SPI实现的,接口是org.apache.dubbo.rpc.cluster.LoadBalance
实现步骤
详情请看负载均衡Demo

  1. 创建类OnlyFirstLoadbalancer并实现LoadBalance接口
public class OnlyFirstLoadbalancer implements LoadBalance {
    @Override
    public <T> Invoker<T> select(List<Invoker<T>> invokers, URL url, Invocation invocation) throws RpcException {
        // 所有的服务提供者 按照IP  + 端口排序   选择第一个
        return invokers.stream().min((i1, i2) -> {
            URL url1 = i1.getUrl();
            URL url2 = i2.getUrl();
            System.out.printf("ip1: %s, port1: %s \n",url1.getIp(), url1.getPort());
            System.out.printf("ip2: %s, port2: %s \n",url2.getIp(), url2.getPort());
            final int ipCompare = url1.getIp().compareTo(url2.getIp());
            if (ipCompare == 0) {
                return Integer.compare(url1.getPort(), url2.getPort());
            }
            return ipCompare;
        }).orElseThrow();
    }
}
  1. 在resouce下创建目录META-INF/dubbo,并创建文件org.apache.dubbo.rpc.cluster.LoadBalance,内容为:
onlyFirst=com.mh.study.dubbo.loadblance.OnlyFirstLoadbalancer
  1. 提供者或消费者添加此负载均衡器
// 提供者
@Service(loadbalance = "onlyFirst")
// 消费者
@Reference(loadbalance = "onlyFirst")

3. 异步调用

主要应用于提供者接口响应耗时明显,消费者端可以利用调用接口的时间去做一些其他的接口调用,利用Future 模式来异步等待和获取结果即可。这种方式可以大大的提升消费者端的利用率。

3.1 异步调用实现

详情请看负载均衡Demo

  1. 在提供者或消费者加异步参数
@Service(async = true)
@Reference(async = true)
  1. 调用
String hello = service.sayHello("world", 200);
// 这里获取的结果是null
System.out.println("result :" + hello);
// 利用Future 模式来获取
Future<Object> future  = RpcContext.getContext().getFuture();
System.out.println("future result:"+future.get());
3.2 异步调用特殊说明

  需要特别说明的是,该方式的使用,请确保dubbo的版本在2.5.4及以后的版本使用。 原因在于在2.5.3及之前的版本使用的时候,会出现异步状态传递问题。 比如我们的服务调用关系是A -> B -> C , 这时候如果A向B发起了异步请求,在错误的版本时,B向C发起的请求也会连带的产生异步请求。这是因为在底层实现层面,他是通过RPCContext 中的attachment 实现的。在A向B发起异步请求时,会在attachment 中增加一个异步标示字段来表明异步等待结果。B在接受到A中的请求时,会通过该字段来判断是否是异步处理。但是由于值传递问题,B向C发起时同样会将该值进行传递,导致C误以为需要异步结果,导致返回空。这个问题在2.5.4及以后的版本进行了修正。

4. 线程池

4.1 Dubbo已有线程池

dubbo在使用时,都是通过创建业务线程池进行操作的,目前已知线程池模型有两个和java中的相对应

  • fix
    • 表示创建固定大小的线程池。也是Dubbo默认的使用方式,默认创建的执行线程数为200,并且是没有任何等待队列的
    • 再极端的情况下可能会存在问题,比如某个操作大量执行时,可能存在堵塞的情况。
  • cache
    • 创建非固定大小的线程池,当线程不足时,会自动创建新的线程。
    • 使用这种的时候需要注意,如果突然有高TPS的请求过来,方法没有及时完成,则会造成大量的线程创建,对系统的CPU和负载都是压力,执行越多反而会拖慢整个系统。
4.2 自定义线程池

  在真实的使用过程中可能会因为使用fix模式的线程池,导致具体某些业务场景因为线程池中的线程数量不足而产生错误,而很多业务研发是对这些无感知的,只有当出现错误的时候才会去查看告警或者通过客户反馈出现严重的问题才去查看,结果发现是线程池满了。
  因此可以在创建线程池的时,通过某些手段对这个线程池进行监控,这样就可以进行及时的扩缩容机器或者告警。
  下面的这个程序就是这样子的,会在创建线程池后进行对其监控,并且及时作出相应处理。

  1. 创建线程池
    这里是基于FixedThreadPool中的实现扩展出线程监控部分

  1. SPI声明,创建文件META-INF/dubbo/org.apache.dubbo.common.threadpool.ThreadPool

  1. 在提供者方配置该线程池生成器
dubbo.provider.threadpool=watching
  1. 接下来模拟整个流程

5. 路由规则

  路由是决定一次请求中需要发往目标机器的重要判断,通过对其控制可以决定请求的目标机器。我们可以通过创建这样的规则来决定一个请求会交给哪些服务器去处理。官方路由文档

5.1 路由规则快速入门
  1. 提供两个提供者(一台本机作为提供者,一台为其他的服务器),每个提供者会在调用时可以返回不同的信息 以区分提供者。
  2. 针对于消费者,我们这里通过一个死循环,每次等待用户输入,再进行调用,来模拟真实的请求情况。
  3. 通过调用的返回值 确认具体的提供者。
  4. 我们通过ipconfig来查询到我们的IP地址,并且单独启动一个客户端,来进行如下配置(这里假设我们希望隔离掉本机的请求,都发送到另外一台机器上)。
public class DubboRouterMain {
    public static void main(String[] args) {
        RegistryFactory registryFactory = ExtensionLoader.getExtensionLoader(RegistryFactory.class).getAdaptiveExtension();
        Registry registry = registryFactory.getRegistry(URL.valueOf("zookeeper://127.0.0.1:2181"));
        registry.register(URL.valueOf("condition://0.0.0.0/com.lagou.service.HelloService?category=routers&force=true&dynamic=true&rule=" + URL.encode("=> host != 你的机器ip不能是127.0.0.1")));
    }
}
  1. 通过这个程序执行后,我们就通过消费端不停的发起请求,看到真实的请求都发到了除去本机以
    外的另外一台机器上。
5.2 路由规则详解
3.5.3 路由与上线系统结合

6. 服务动态降级

6.1 什么是服务降级
6.2 为什么要服务降级

四、Dubbo源码剖析

1. 搭建源码环境

  1. 源码下载地址Dubbo2.7.5版本
  2. cd dubbo-dubbo-2.7.5
  3. 编译 mvn clean install -DskipTests=true
  4. 导入到idea

2. 架构整体设计

2.1 Dubbo调用关系说明
2.2 整体调用链路
2.3 Dubbo整体源码设计

3. 服务注册与消费源码剖析

3.1 注册中心Zookeeper剖析

注册中心是Dubbo的重要组成部分,主要用于服务的注册与发现,我们可以选择Redis、Nacos、
Zookeeper作为Dubbo的注册中心,Dubbo推荐用户使用Zookeeper作为注册中心。

Zookeeper作为Dubbo的注册中心的目录结构

Zookeeper的数据节点层级如下:

+- dubbo
| +- 服务的全限定类名
| | +- consumers
| | | +- 消费者URL
| | +- providers
| | | +- 提供者URL
| | +- configuration
| | +- routers

configuration: 当前服务下面的配置信息信息,provider或者consumer会通过读取这里的配
置信息来获取配置。

routers: 当消费者在进行获取提供者的时,会通过这里配置好的路由来进行适配匹配规则。

Dubbo是以URL的形式使提供者和消费者交互的,而URL里以参数的形式保存很多信息。

在这里插入图片描述

  • 提供者会在providers 目录下进行自身的进行注册。
  • 消费者会在consumers 目录下进行自身注册,并且监听provider 目录,以此通过监听提供者增
    加或者减少,实现服务发现。
  • Monitor模块会对整个服务级别做监听,用来得知整体的服务情况。以此就能更多的对整体情况做
    监控。

以HelloService为例,数据节点层级如下:


3.2 服务的注册过程分析

服务注册暴露过程
在这里插入图片描述

  • 首先 ServiceConfig 类拿到对外提供服务的实际类 ref(如:HelloServiceImpl)

  • 然后通过ProxyFactory 接口实现类中的 getInvoker 方法使用 ref 生成一个 AbstractProxyInvoker 实例

  • 到这一步就完成具体服务到 Invoker 的转化。接下来就是 Invoker 转换到 Exporter 的过程。

重点剖析一下Invoker 转换成 Exporter的过程

其中会涉及到 RegistryService接口 RegistryFactory接口和注册provider到注册中心流程的过程。

(1) RegistryService代码解读,这块儿的代码比较简单,主要是对指定的路径进行注册,解绑,监听和
取消监听,查询操作。也是注册中心中最为基础的类。

public interface RegistryService {
    void register(URL url);
    void unregister(URL url);
    List<URL> lookup(URL url);
}

(2) 我们再来看RegistryFactory,是通过他来生成真实的注册中心。通过这种方式,也可以保证一
个应用中可以使用多个注册中心。可以看到这里也是通过不同的protocol参数,来选择不同的协议。

@SPI("dubbo")
public interface RegistryFactory {
    @Adaptive({"protocol"})
    Registry getRegistry(URL url);
}

(3) 下面我们就来跟踪一下,一个服务是如何注册到注册中心上去的。其中比较关键的一个类是
RegistryProtocol,他负责管理整个注册中心相关协议。并且统一对外提供服务。这里我们主要以
RegistryProtocol.export 方法作为入口,这个方法主要的作用就是将我们需要执行的信息注册并且
导出。

以下时序图只列举一些关键的方法,方便说明

@Override
public <T> Exporter<T> export(final Invoker<T> originInvoker) throws RpcException {
    // 获取注册中心的地址
    URL registryUrl = getRegistryUrl(originInvoker);
    // 获取当前提供者需要注册的地址
    URL providerUrl = getProviderUrl(originInvoker);
    // 获取进行注册override协议的访问地址
    final URL overrideSubscribeUrl = getSubscribedOverrideUrl(providerUrl);
    // 增加override的监听器
    final OverrideListener overrideSubscribeListener = new OverrideListener(overrideSubscribeUrl, originInvoker);
    overrideListeners.put(overrideSubscribeUrl, overrideSubscribeListener);
    // 根据现有的override协议,对注册地址进行改写操作
    providerUrl = overrideUrlWithConfig(providerUrl, overrideSubscribeListener);
    //export invoker 完成后即可在看到本地的20880端口号已经启动,并且暴露服务
    final ExporterChangeableWrapper<T> exporter = doLocalExport(originInvoker, providerUrl);

    // 获取真实的注册中心, 比如我们常用的ZookeeperRegistry
    final Registry registry = getRegistry(originInvoker);
    // 获取当前服务需要注册到注册中心的providerURL,主要用于去除一些没有必要的参数(比如在本地导出时所使用的qos参数等值)
    final URL registeredProviderUrl = getUrlToRegistry(providerUrl, registryUrl);
    // 决定是否需要延迟发布
    boolean register = providerUrl.getParameter(REGISTER_KEY, true);
    if (register) {
        // 将当前的提供者注册到注册中心上去
        register(registryUrl, registeredProviderUrl);
    }

    // Deprecated! Subscribe to override rules in 2.6.x or before.
    registry.subscribe(overrideSubscribeUrl, overrideSubscribeListener);

    exporter.setRegisterUrl(registeredProviderUrl);
    exporter.setSubscribeUrl(overrideSubscribeUrl);
    //Ensure that a new exporter instance is returned every time export
    return new DestroyableExporter<>(exporter);
}

(4)下面我们再来看看register 方法, 这里面做的比较简单,主要是从RegistoryFactory 中获取注
册中心,并且进行地址注册。

public void register(URL registryUrl, URL registeredProviderUrl) {
    // 获取注册中心
    Registry registry = registryFactory.getRegistry(registryUrl);
    // 对当前的服务进行注册
    registry.register(registeredProviderUrl);
    // ProviderModel 表示服务提供者模型,此对象中存储了与服务提供者相关的信息。
    // 比如服务的配置信息,服务实例等。每个被导出的服务对应一个 ProviderModel
    ProviderModel model = ApplicationModel.getProviderModel(registeredProviderUrl.getServiceKey());
    model.addStatedUrl(new ProviderModel.RegisterStatedURL(
        registeredProviderUrl,
        registryUrl,
        true
    ));
}

(5) 这里我们再跟里面的register方法之前,先来介绍一下Registry中的类目录结构

在这里插入图片描述

  • RegistryService 对外提供注册机制的接口。
  • AbstractRegistry 是对注册中心的封装,其主要会对本地注册地址的封装,主要功能在于远程
    注册中心不可用的时候,可以采用本地的注册中心来使用。
  • FailbackRegistry 从名字中可以看出来,失败自动恢复,后台记录失败请求,定时重发功能。
  • FailbackRegistry则更多是真实的第三方渠道实现。

(6) 下面我们来看一下在FailbackRegistry 中的实现, 可以在这里看到他的主要作用是调用第三方的
实现方式,并且在出现错误时增加重试机制。

public void register(URL url) {
    if (!acceptable(url)) {
        logger.info("URL " + url + " will not be registered to Registry. Registry " + url + " does not accept service of this protocol type.");
        return;
    }
    // 主要用于保存已经注册的地址列表    
    super.register(url);
    // 将一些错误的信息移除(确保当前地址可以在出现一些错误的地址时可以被删除)
    removeFailedRegistered(url);
    removeFailedUnregistered(url);
    try {
        // 向服务器端发送注册请求
        doRegister(url);
    } catch (Exception e) {
        Throwable t = e;

        // 记录日志
        // If the startup detection is opened, the Exception is thrown directly.
        boolean check = getUrl().getParameter(Constants.CHECK_KEY, true)
            && url.getParameter(Constants.CHECK_KEY, true)
            && !CONSUMER_PROTOCOL.equals(url.getProtocol());
        boolean skipFailback = t instanceof SkipFailbackWrapperException;
        if (check || skipFailback) {
            if (skipFailback) {
                t = t.getCause();
            }
            throw new IllegalStateException("Failed to register " + url + " to registry " + getUrl().getAddress() + ", cause: " + t.getMessage(), t);
        } else {
            logger.error("Failed to register " + url + ", waiting for retry, cause: " + t.getMessage(), t);
        }

        // 将失败的注册请求记录到失败列表中,定期重试
        addFailedRegistered(url);
    }
}

(7) 下面我们再来看看ZookeeperRegistry#doRegister方法的实现, 可以看到这里的实现也比较简单,关键
在于toUrlPath 方法的实现。关于dynamic 的值。

public void doRegister(URL url) {
    try {
        zkClient.create(toUrlPath(url), url.getParameter(DYNAMIC_KEY, true));
    } catch (Throwable e) {
        throw new RpcException("Failed to register " + url + " to zookeeper " + getUrl() + ", cause: " + e.getMessage(), e);
    }
}

(8) 解读toUrlPath 方法。可以看到这里的实现也是比较简单,也验证了我们之前的路径规则。

private String toUrlPath(URL url) {
    return toCategoryPath(url) + PATH_SEPARATOR + URL.encode(url.toFullString());
}
3.3 URL规则详解和服务本地缓存

URL规则详解

格式:protocol://host:port/path?key=value&key=value

示例:

provider://192.168.20.1:20883/com.lagou.service.HelloService?
anyhost=true&application=serviceprovider2&
bind.ip=192.168.20.1&bind.port=20883&category=configurators&check=fals
e&deprecated=false&dubbo=2.0.2&dynamic=true&generic=false&interface=com.lagou.se
rvice

URL主要有以下几部分组成:

  • protocol: 协议,一般像我们的provider 或者consumer 在这里都认为是具体的协议
  • host: 当前provider 或者其他协议所具体针对的地址,比较特殊的像override 协议所指定的host就是0.0.0.0 代表所有的机器都生效
  • port: 和上面相同,代表所处理的端口号
  • path: 服务路径,在provider 或者consumer 等其他中代表着我们真实的业务接口
  • key=value: 这些则代表具体的参数,这里我们可以理解为对这个地址的配置。比如我们provider中需要具体机器的服务应用名,就可以是一个配置的方式设置上去。

服务本地缓存

dubbo调用者需要通过注册中心(例如:ZK)注册信息,获取提供者,但是如果频繁往从ZK获取信
息,肯定会存在单点故障问题,所以dubbo提供了将提供者信息缓存在本地的方法。

Dubbo在订阅注册中心的回调处理逻辑当中会保存服务提供者信息到本地缓存文件当中(同步/异步两
种方式),以URL维度进行全量保存。

Dubbo在服务引用过程中会创建registry对象并加载本地缓存文件,会优先订阅注册中心,订阅注册中
心失败后会访问本地缓存文件内容获取服务提供信息。

(1) 首先从构造方法讲起, 这里方法比较简单,主要用于确定需要保存的文件信息。并且从系统中读取
已有的配置信息。

public AbstractRegistry(URL url) {
    setUrl(url);
    // Start file save timer
    syncSaveFile = url.getParameter(REGISTRY_FILESAVE_SYNC_KEY, false);
    // 默认保存路径   
    String defaultFilename = System.getProperty("user.home") + "/.dubbo/dubbo-registry-" + url.getParameter(APPLICATION_KEY) + "-" + url.getAddress().replaceAll(":", "-") + ".cache";
    String filename = url.getParameter(FILE_KEY, defaultFilename);
    File file = null;
    if (ConfigUtils.isNotEmpty(filename)) {
        file = new File(filename);
        if (!file.exists() && file.getParentFile() != null && !file.getParentFile().exists()) {
            if (!file.getParentFile().mkdirs()) {
                throw new IllegalArgumentException("Invalid registry cache file " + file + ", cause: Failed to create directory " + file.getParentFile() + "!");
            }
        }
    }
    this.file = file;
    // When starting the subscription center,
    // we need to read the local cache file for future Registry fault tolerance processing.
    // 加载已有的配置文件
    loadProperties();
    notify(url.getBackupUrls());
}

(2)我们可以看到这个类中最为关键的一个属性为properties ,我们可以通过寻找,得知这个属性
的设置值只有在一个地方: saveProperties ,我们来看一下这个方法。这里也有一个我们值得关注的
点,就是基于版本号的的更改

private void saveProperties(URL url) {
    if (file == null) {
        return;
    }

    try {
        StringBuilder buf = new StringBuilder();
        // 获取所有通知到的地址
        Map<String, List<URL>> categoryNotified = notified.get(url);
        if (categoryNotified != null) {
            for (List<URL> us : categoryNotified.values()) {
                for (URL u : us) {
                    // 多个地址进行拼接
                    if (buf.length() > 0) {
                        buf.append(URL_SEPARATOR);
                    }
                    buf.append(u.toFullString());
                }
            }
        }
        // 保存数据
        properties.setProperty(url.getServiceKey(), buf.toString());
        // 保存为一个新的版本号
		// 通过这种机制可以保证后面保存的记录,在重试的时候,不会重试之前的版本
        long version = lastCacheChanged.incrementAndGet();
        if (syncSaveFile) {
            // 同步保存
            doSaveProperties(version);
        } else {
            // 异步保存
            registryCacheExecutor.execute(new SaveProperties(version));
        }
    } catch (Throwable t) {
        logger.warn(t.getMessage(), t);
    }
}

(3) 下面我们再来看看是如何进行保存文件的。这里的实现也比较简单,主要比较关键的代码在于利
用文件级锁来保证同一时间只会有一个线程执行。

public void doSaveProperties(long version) {
    if (version < lastCacheChanged.get()) {
        return;
    }
    if (file == null) {
        return;
    }
    // Save
    try {
        // 使用文件对象为锁,来保证同一段时间只会有一个线程进行读取操作
        File lockfile = new File(file.getAbsolutePath() + ".lock");
        if (!lockfile.exists()) {
            lockfile.createNewFile();
        }
        try (RandomAccessFile raf = new RandomAccessFile(lockfile, "rw");
            FileChannel channel = raf.getChannel()) {
            // 利用文件锁来保证并发的执行的情况下,只会有一个线程执行成功(原因在于可能是跨VM的)
            FileLock lock = channel.tryLock();
            if (lock == null) {
                throw new IOException("Can not lock the registry cache file " + file.getAbsolutePath() + ", ignore and retry later, maybe multi java process use the file, please config: dubbo.registry.file=xxx.properties");
            }
            // Save
            try {
                if (!file.exists()) {
                    file.createNewFile();
                }
                // 将配置的文件信息保存到文件中
                try (FileOutputStream outputFile = new FileOutputStream(file)) {
                    properties.store(outputFile, "Dubbo Registry Cache");
                }
            } finally {
                // 解开文件锁
                lock.release();
            }
        }
    } catch (Throwable e) {
        // 执行出现错误时,则交给专门的线程去进行重试
        savePropertiesRetryTimes.incrementAndGet();
        if (savePropertiesRetryTimes.get() >= MAX_RETRY_TIMES_SAVE_PROPERTIES) {
            logger.warn("Failed to save registry cache file after retrying " + MAX_RETRY_TIMES_SAVE_PROPERTIES + " times, cause: " + e.getMessage(), e);
            savePropertiesRetryTimes.set(0);
            return;
        }
        if (version < lastCacheChanged.get()) {
            savePropertiesRetryTimes.set(0);
            return;
        } else {
            registryCacheExecutor.execute(new SaveProperties(lastCacheChanged.incrementAndGet()));
        }
        logger.warn("Failed to save registry cache file, will retry, cause: " + e.getMessage(), e);
    }
}
3.4 Dubbo 消费过程分析

服务消费流程

在这里插入图片描述

首先 ReferenceConfig#init 方法调用 createProxy() ,期间 使用Protocol 调用 refer 方法生
Invoker 实例(如上图中的红色部分),这是服务消费的关键。接下来使用ProxyFactory把 Invoker
转换为客户端需要的接口(如:HelloService)。

4. Dubbo扩展SPI源码剖析

SPI在之前都有使用过,其中最重要的类就是ExtensionLoader ,它是所有Dubbo中SPI的入口。
这里主要介绍ExtensionLoader.getExtensionLoaderExtensionLoader.getExtension方法

4.1 getExtensionLoader加载过程

(1) 先从map中获取ExtensionLoader实例,如果没有则新创建

public static <T> ExtensionLoader<T> getExtensionLoader(Class<T> type) {
    if (type == null) {
        throw new IllegalArgumentException("Extension type == null");
    }
    if (!type.isInterface()) {
        throw new IllegalArgumentException("Extension type (" + type + ") is not an interface!");
    }
    if (!withExtensionAnnotation(type)) {
        throw new IllegalArgumentException("Extension type (" + type +
                                           ") is not an extension, because it is NOT annotated with @" + SPI.class.getSimpleName() + "!");
    }
	// 先从缓存中获取
    ExtensionLoader<T> loader = (ExtensionLoader<T>) EXTENSION_LOADERS.get(type);
    if (loader == null) {
        // 创建新的ExtensionLoader放入到map中
        EXTENSION_LOADERS.putIfAbsent(type, new ExtensionLoader<T>(type));
        loader = (ExtensionLoader<T>) EXTENSION_LOADERS.get(type);
    }
    return loader;
}

(2) 获取ExtensionFactory实例

private ExtensionLoader(Class<?> type) {
    this.type = type;
    objectFactory = (type == ExtensionFactory.class ? null : ExtensionLoader.getExtensionLoader(ExtensionFactory.class).getAdaptiveExtension());
}

(3) ExtensionFactory是通过传入扩展点类型和真正的名称来获取扩展的。基于SPI获取ExtensionFactory实例

@SPI
public interface ExtensionFactory {

    /**
     * Get extension.
     *
     * @param type object type.
     * @param name object name.
     * @return object instance.
     */
    <T> T getExtension(Class<T> type, String name);

}

(4) 可以在dubbo-common/src/main/resources/METAINF/
dubbo/internal/org.apache.dubbo.common.extension.ExtensionFactory 中看到

adaptive=org.apache.dubbo.common.extension.factory.AdaptiveExtensionFactory
spi=org.apache.dubbo.common.extension.factory.SpiExtensionFactory

(5) 可以看到在 AdaptiveExtensionFactory 中是使用 @Adaptive 标记的。这里可以通过类名基本看出来,他其实最主要的作用是进行代理其他的ExtensionFactory。其中比较重要的方法在于 getSupportedExtensions 方法,获取所有支持的扩展信息实现。

@Adaptive
public class AdaptiveExtensionFactory implements ExtensionFactory {

    private final List<ExtensionFactory> factories;

    public AdaptiveExtensionFactory() {
        ExtensionLoader<ExtensionFactory> loader = ExtensionLoader.getExtensionLoader(ExtensionFactory.class);
        List<ExtensionFactory> list = new ArrayList<ExtensionFactory>();
        // 获取支持的扩展
        for (String name : loader.getSupportedExtensions()) {
            // 将所有的ExtensionFactory进行缓存
            list.add(loader.getExtension(name));
        }
        factories = Collections.unmodifiableList(list);
    }

    @Override
    public <T> T getExtension(Class<T> type, String name) {
        for (ExtensionFactory factory : factories) {
            T extension = factory.getExtension(type, name);
            if (extension != null) {
                return extension;
            }
        }
        return null;
    }

}

(6) 获取所有支持的扩展信息实现: ExtensionLoader.getSupportedExtensions ,这里可以看到,其实比较关键的方法在于getExtensionClasses 方法

public Set<String> getSupportedExtensions() {
    Map<String, Class<?>> clazzes = getExtensionClasses();
    return Collections.unmodifiableSet(new TreeSet<>(clazzes.keySet()));
}

(7) 观察getExtensionClasses的实现,可以看到这里其实主要做的就是一件事情,防止重复被加载,所以真正的的实现还需要专门去查看loadExtensionClasses 方法,在我们通过名称获取扩展类之前,首先需要根据配置文件解析出扩展类名称到扩展类的映射关系表classes之后再根据扩展项名称 从映射关系表中获取取对应的扩展类即可。

private Map<String, Class<?>> getExtensionClasses() {
    Map<String, Class<?>> classes = cachedClasses.get();
    if (classes == null) {
        synchronized (cachedClasses) {
            classes = cachedClasses.get();
            if (classes == null) {
                // 进行加载信息 加载扩展类
                classes = loadExtensionClasses();
                cachedClasses.set(classes);
            }
        }
    }
    return classes;
}

(8) 观察ExtensionLoader#loadExtensionClasses方法实现。

这里主要做了两件事情。1: 加载当前SPI的默认实现。2:加载这个类的所有扩展点实现,并且按照name和Class对象的形式存储

private Map<String, Class<?>> loadExtensionClasses() {
    // 加载默认扩展的实现名称
    cacheDefaultExtensionName();
	// 获取其中每一种实现的名称和对应的classes
    Map<String, Class<?>> extensionClasses = new HashMap<>();
    // internal extension load from ExtensionLoader's ClassLoader first
    loadDirectory(extensionClasses, DUBBO_INTERNAL_DIRECTORY, type.getName(), true);
    loadDirectory(extensionClasses, DUBBO_INTERNAL_DIRECTORY, type.getName().replace("org.apache", "com.alibaba"), true);

    loadDirectory(extensionClasses, DUBBO_DIRECTORY, type.getName());
    loadDirectory(extensionClasses, DUBBO_DIRECTORY, type.getName().replace("org.apache", "com.alibaba"));
    loadDirectory(extensionClasses, SERVICES_DIRECTORY, type.getName());
    loadDirectory(extensionClasses, SERVICES_DIRECTORY, type.getName().replace("org.apache", "com.alibaba"));
    return extensionClasses;
}

ExtensionLoader#loadDirectory,主要功能是从这个文件夹中寻找真正的文件列表,并且对其中的文件内容解析并且放入到extensionClasses Map中具体解析文件的内容实现,还要参考loadResource 实现

private void loadDirectory(Map<String, Class<?>> extensionClasses, String dir, String type, boolean extensionLoaderClassLoaderFirst) {
   
    // ... 省图若干源码
    
        if (urls != null) {
            while (urls.hasMoreElements()) {
                java.net.URL resourceURL = urls.nextElement();
                // 加载资源信息到extensionClasses, 主要功能是读取文件内容
                loadResource(extensionClasses, classLoader, resourceURL);
            }
        }
    } catch (Throwable t) {
        logger.error("Exception occurred when loading extension class (interface: " +
                     type + ", description file: " + fileName + ").", t);
    }
}

(9)进行观察ExtensionLoader#loadResource实现,主要是用于读取文件操作,并且将方法交由loadClass 来加载类信息。加载类信息也是最重要的方法所在。

4.2 根据name获取扩展点的方法 getExtension
4.3 Adaptive功能实现原理

Adaptive的主要功能是对所有的扩展点进行封装为一个类,通过URL传入参数的时动态选择需要使用的扩展点。其底层的实现原理就是动态代理。
以下代码是使用Adaptive功能的一个示例

public class DubboAdaptiveMain {
    public static void main(String[] args) {
        URL url = URL.valueOf("test://localhost/hello?hello.service=human");
        HelloService adaptiveExtension = ExtensionLoader.getExtensionLoader(HelloService.class).getAdaptiveExtension();
        String msg = adaptiveExtension.sayHello(url);
        System.out.println(msg);
    }
}

ExtensionLoader#getAdaptiveExtension获取Adaptive扩展

调用者 ExtensionLoader Holder ExtensionFactory Class getAdaptiveExtension get获取缓存的instance instance createAdaptiveExtension getAdaptiveExtensionClass 返回扩展Class newInstance instance injectExtension给实例注入扩展 getExtension obj即需要注入的扩展点 loop [instance.getClass().getMetods()] intance instance instance 调用者 ExtensionLoader Holder ExtensionFactory Class
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值