Dubbo

Apache Dubbo 是一款微服务开发框架,它提供了 RPC 通信与微服务治理两大关键能力。这意味着,使用 Dubbo 开发的微服务,将具备相互之间的远程发现与通信能力,同时利用 Dubbo 提供的丰富服务治理能力,可以实现诸如服务发现、负载均衡、流量调度等服务治理诉求。同时 Dubbo 是高度可扩展的,用户几乎可以在任意功能点去定制自己的实现,以改变框架的默认行为来满足自己的业务需求。

Dubbo 的核心价值在于:用**一套统一的 RPC 与治理模型**,让分布式服务之间的远程调用、服务发现与流量治理变得简单可控,从而支撑超大规模微服务架构的落地与演进。

传统单体应用把所有逻辑耦合在一起,服务拆分后面临着远程调用、服务发现与流量治理等难题;Dubbo 正是为解决“微服务之间如何高效、可靠地通信与治理”这一痛点而生。
Dubbo 3.x

1. 概述

Apache Dubbo 是一款微服务开发框架,提供了 RPC 通信与微服务治理两大关键能力。使用 Dubbo 开发的微服务可以具备相互之间的远程发现与通信能力,并通过服务发现、负载均衡、流量调度等治理能力满足分布式治理诉求。Dubbo 高度可扩展,用户几乎可以在任意功能点定制实现,用一套统一的 RPC 与治理模型支撑超大规模微服务架构的落地与演进。

2. 简介

Apache Dubbo 是一款微服务开发框架,它提供了 RPC 通信与微服务治理两大关键能力。这意味着,使用 Dubbo 开发的微服务,将具备相互之间的远程发现与通信能力,同时利用 Dubbo 提供的丰富服务治理能力,可以实现诸如服务发现、负载均衡、流量调度等服务治理诉求。同时 Dubbo 是高度可扩展的,用户几乎可以在任意功能点去定制自己的实现,以改变框架的默认行为来满足自己的业务需求。

1.1 Dubbo3 的演进

Dubbo3 基于 Dubbo2 演进而来,在保持原有核心功能特性的同时,Dubbo3 在易用性、超大规模微服务实践、云原生基础设施适配、安全设计等几大方向上进行了全面升级。以下文档都将基于 Dubbo3 展开。

**定位** Dubbo 同时具备 RPC 通信与微服务治理能力,既能解决服务间远程调用,也能提供服务发现、负载均衡、流量调度等治理特性。

3. ZooKeeper 注册中心

Dubbo 通常依赖注册中心来实现服务的注册与发现,ZooKeeper 是常用的注册中心之一。

2.1 安装 ZooKeeper

到 ZooKeeper 稳定版下载地址 下载 ZooKeeper,目前的最新版是 3.5.6。

把 apache-zookeeper-3.5.6-bin.tar.gz 解压到一个本地目录(目录名最好不要包含空格和中文)。示例使用 /usr/local 目录:

tar -zxvf apache-zookeeper-3.8.4-bin.tar.gz

把 conf 目录下的 zoo_sample.cfg 重命名为 zoo.cfg,然后修改配置:

cp zoo_sample.cfg zoo.cfg
mkdir zoodata

zoo.cfg 关键配置如下(其中 tickTime 为心跳检查时间,单位毫秒):

# 心跳检查的时间 2秒
tickTime=2000
# 初始化时 连接到服务器端的间隔次数,总时间10*2=20秒
initLimit=10
# ZK Leader 和follower 之间通讯的次数,总时间5*2=10秒
syncLimit=5
# 存储内存中数据快照的位置,如果不设置参数,更新事务日志将被存储到默认位置。
dataDir=/root//root/apache-zookeeper-3.8.4-bin/zoodata
# ZK 服务器端的监听端口  
clientPort=2181

配置以下环境变量(vim /etc/profile):

export ZOOKEEPER_HOME=/root/apache-zookeeper-3.8.4-bin
export PATH=$PATH:$ZOOKEEPER_HOME/bin:$ZOOKEEPER_HOME/conf
source /etc/profile
**目录建议** 解压 ZooKeeper 的目录名最好不要包含空格和中文,以免引发路径解析问题。

2.2 启动与停止 ZooKeeper

安装配置完成后,使用 zkServer.sh start 启动 ZooKeeper 服务:

[root@wupx apache-zookeeper-3.5.6-bin]# ./zkServer.sh start
/usr/bin/java
ZooKeeper JMX enabled by default
Using config: /usr/local/apache-zookeeper-3.5.6-bin/bin/../conf/zoo.cfg
Starting zookeeper ... STARTED

常用运维命令如下:

命令 说明
./zkServer.sh start 启动 ZooKeeper 服务
./zkServer.sh status 查看 ZooKeeper 运行状态
./zkServer.sh stop 停止 ZooKeeper 服务
# 查看状态
./zkServer.sh status

# 停止 ZooKeeper
./zkServer.sh stop

4. 使用 Dubbo

下面演示如何在 Spring/Spring MVC 与 Spring Boot 项目中接入 Dubbo,并安装 dubbo-admin 控制台。

3.1 引入依赖

新建 Spring 和 Spring MVC 项目,并在 pom.xml 中引入相关依赖(servlet 3.0 规范、Spring、日志、Dubbo 以及 ZooKeeper 客户端 Curator):

<properties>
      <spring.version>5.1.9.RELEASE</spring.version>
      <dubbo.version>2.7.4.1</dubbo.version>
      <zookeeper.version>4.0.0</zookeeper.version>
  </properties>

  <dependencies>
      <!--servlet 3.0规范-->
      <dependency>
          <groupId>javax.servlet</groupId>
          <artifactId>javax.servlet-api</artifactId>
          <version>3.1.0</version>
          <scope>provided</scope>
      </dependency>

      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-context</artifactId>
          <version>${spring.version}</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-webmvc</artifactId>
          <version>${spring.version}</version>
      </dependency>

      <dependency>
          <groupId>org.slf4j</groupId>
          <artifactId>slf4j-api</artifactId>
          <version>1.7.33</version>
      </dependency>
      <dependency>
          <groupId>org.slf4j</groupId>
          <artifactId>slf4j-log4j12</artifactId>
          <version>1.7.33</version>
      </dependency>

      <dependency>
          <groupId>org.apache.dubbo</groupId>
          <artifactId>dubbo</artifactId>
          <version>${dubbo.version}</version>
      </dependency>
      <dependency>
          <groupId>org.apache.curator</groupId>
          <artifactId>curator-framework</artifactId>
          <version>${zookeeper.version}</version>
      </dependency>
      <dependency>
          <groupId>org.apache.curator</groupId>
          <artifactId>curator-recipes</artifactId>
          <version>${zookeeper.version}</version>
      </dependency>
  </dependencies>

3.2 配置文件

在 resources 目录下创建 Spring.xml,声明 Dubbo 应用名、注册中心地址与包扫描:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:dubbo="http://dubbo.apache.org/schema/dubbo" xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://dubbo.apache.org/schema/dubbo http://dubbo.apache.org/schema/dubbo/dubbo.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

<!--    <context:component-scan base-package="com.richu.service"/> -->
    <!--项目名-->
    <dubbo:application name="dubbo-server"/>
    <!--注册中心地址-->
    <dubbo:registry address="zookeeper://192.168.3.133:2181"/>
    <!--包扫描-->
    <dubbo:annotation package="com.richu.service"/>
</beans>

在 webapp/WEB-INF/ 下创建 web.xml,配置 Spring 容器监听:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <!-- 配置spring -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:Spring.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
</web-app>

添加 @DubboService 注解暴露服务实现:

@DubboService
public class UserServiceImpl implements UserService {
    @Override
    public String login(String username, String password) {
        return "test login";
    }
}

3.3 Spring Boot 使用 Dubbo

定义可序列化的 User 类与 UserService 接口:

@Data
public class User implements Serializable {
    private static final long serialVersionUID = -9206514891359830486L;
    private int id;
    private String name;
    private String sex;
}
public interface UserService {
    User getUser(int id);
}

新建两个 Spring Boot 项目,一个是服务提供者,一个是服务消费者,引入 Dubbo 核心依赖。注意排除 Curator 自带的 ZooKeeper 依赖,改用自己指定的 ZooKeeper 版本:

<dependency>
    <groupId>org.apache.dubbo</groupId>
    <artifactId>dubbo-spring-boot-starter</artifactId>
    <version>2.7.4.1</version>
</dependency>
<dependency>
    <groupId>org.apache.curator</groupId>
    <artifactId>curator-framework</artifactId>
    <version>4.0.0</version>
</dependency>
<dependency>
    <groupId>org.apache.curator</groupId>
    <artifactId>curator-recipes</artifactId>
    <version>4.0.0</version>
    <exclusions>
        <exclusion>
            <groupId>org.apache.zookeeper</groupId>
            <artifactId>zookeeper</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>org.apache.zookeeper</groupId>
    <artifactId>zookeeper</artifactId>
    <version>3.4.14</version>
</dependency>

服务提供者的配置写在 application.yaml 中:

dubbo:
  application:
    name: dubbo-provider
  registry:
    address: zookeeper://127.0.0.1:2181
  protocol:
    name: dubbo
    port: 20880

服务提供者需要写服务实现类,注意 @Service 注解采用的是 Dubbo 包下的:

import org.apache.dubbo.config.annotation.Service;
import org.springframework.stereotype.Component;

@Service
@Component
public class UserServiceImpl implements UserService {
    @Override
    public User getUser(int id) {
        User user=new User();
        user.setId(id);
        user.setName("javayz");
        user.setSex("man");
        return user;
    }
}

接着在启动类上添加一个 @EnableDubbo 注解即可。

服务消费者同样先写配置文件:

dubbo:
  application:
    name: dubbo-consumer
  registry:
    address: zookeeper://127.0.0.1:2181

在 UserController 中通过 @Reference 注解将 service 对象引进来:

@RestController
@RequestMapping("/user")
public class UserController {

    @Reference
    private UserService userService;

    @GetMapping("/{id}")
    public User getUser(@PathVariable int id) {
        return userService.getUser(id);
    }
}

访问 http://localhost:8081/user/1,返回结果如下:

{
  "id": 1,
  "name": "hello",
  "sex": "man"
}
**注解来源** 服务提供者端的 `@Service` 要使用 `org.apache.dubbo.config.annotation.Service`,而不是 Spring 的 `@Service`,否则不会被 Dubbo 暴露为远程服务。

3.4 安装 dubbo-admin

从 https://github.com/apache/dubbo-admin 下载并解压,需要提前准备好 Maven 和 Node 环境:

# 使用 maven 打包
mvn clean package
# 或跳过测试打包
mvn clean package -Dmaven.test.skip=true

# 打包后用 java -jar 执行(推荐使用 java8 或 11)
java -jar dubbo-admin-*.jar

在 ui 模块中可直接使用其 node 文件夹下的 node.exe,然后通过 npm run dev 启动前端,默认访问地址为 http://localhost:38082/。

操作 命令 说明
后端打包 mvn clean package -Dmaven.test.skip=true 跳过测试快速打包
后端运行 java -jar xxx 运行打包后的后端(推荐 java8/11)
前端启动 npm run dev 启动前端,默认 http://localhost:38082/
**运行环境** dubbo-admin 后端推荐使用 Java 8 或 Java 11 运行,避免高版本 JDK 兼容性问题。

5. Dubbo 高级特性

4.1 重试、超时与多版本

Dubbo 支持声明式的重试与超时控制:

@Service(timeout = 5000,retries = 10)

多版本控制可通过 version 属性区分不同实现,消费方在注入时指定所需版本:

@Service(timeout = 5000,retries = 10,version = "v2.0")
@Service(timeout = 5000,retries = 10,version = "v1.0")

//注入的时候指定版本
@Reference(version = "v1.0")
private UserService userService;

4.2 负载均衡策略

Dubbo 提供多种负载均衡策略,详见 官方负载均衡文档。权重可通过 @Service(weight = ...) 配置:

//配置权重
@Service(weight = 100)
@Service(weight = 200)
@Service(weight = 300)
负载均衡策略 说明
random Dubbo 默认策略,加权随机负载均衡
roundrobin 轮询,可在全局、接口级、方法级配置
consistenthash 一致性哈希,默认取第一个参数作为哈希 key

4.2.1 全局配置

Dubbo 框架的默认策略是 random 加权随机负载均衡。如果要调整策略,只需设置 loadbalance 相应取值即可。

为所有服务调用指定全局配置:

dubbo:
  consumer:
    loadbalance: roundrobin

4.2.2 接口级配置

可以为每个服务指定不同的负载均衡策略。

在 provider 端设置,作为 consumer 侧默认值:

@DubboService(loadbalance = "roundrobin")
public class DemoServiceImpl implements DemoService {}

在 consumer 端设置,具备更高优先级:

@DubboReference(loadbalance = "roundrobin")
private DemoService demoService;

4.2.3 方法级配置

也可以指定方法(method)级别的负载均衡策略。在 Spring Boot 开发模式下,配置 method 级别参数有以下几种方式:

JavaConfig

@Configuration
public class DubboConfiguration {
    @Bean
    public ServiceBean demoService() {
    	MethodConfig method = new MethodConfig();
    method.setName("sayHello");
    method.setLoadbalance("roundrobin");

        ServiceBean service = new ServiceBean();
        service.setInterface(DemoService.class);
        service.setRef(new DemoServiceImpl());
        service.addMethod(method)
        return service;
    }
}
@Autowired
private DemoService demoService;

@Configuration
public class DubboConfiguration {
    @Bean
    public ReferenceBean demoService() {
    	MethodConfig method = new MethodConfig();
  method.setName("sayHello");
  method.setLoadbalance("roundrobin");

        ReferenceBean<DemoService> reference = new ReferenceBean<>();
  reference.setInterface(DemoService.class);
  reference.addMethod(method);
        return reference;
    }
}

dubbo.properties

dubbo.reference.org.apache.dubbo.samples.api.DemoService.sayHello.loadbalance=roundrobin

4.2.4 一致性哈希配置

默认采用第一个参数作为哈希 key,如果需要切换参数,可以指定 hash.arguments 属性:

ReferenceConfig<DemoService> referenceConfig = new ReferenceConfig<DemoService>();
// ... init
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("hash.arguments", "1");
parameters.put("sayHello.hash.arguments", "0,1");
referenceConfig.setParameters(parameters);
referenceConfig.setLoadBalance("consistenthash");
referenceConfig.get();

4.3 限流策略配置

Dubbo 支持在服务器端和消费端按服务粒度或方法粒度限制并发执行数(占用线程池线程数或连接数)。

4.3.1 限制服务器端并发执行数(服务粒度)

限制 com.richu.UserService 的每个方法,服务器端并发执行(或占用线程池线程数)不能超过 10 个:

@DubboService(executes=10)
private UserServiceImpl implements UserService{}

4.3.2 限制服务器端并发执行数(方法粒度)

限制 com.richu.UserService 的 sayHello 方法,服务器端并发执行(或占用线程池线程数)不能超过 10 个:

@DubboService(executes=10, methods = {@Method(name="sayHello",executes=10)})
private UserServiceImpl implements UserService{}

4.3.3 限制消费端并发调用数(服务粒度)

限制 com.richu.UserService 的每个方法,每客户端并发执行(或占用连接的请求数)不能超过 10 个:

@DubboReference(actives=10)
private UserService userService;

4.3.4 限制消费端并发调用数(方法粒度)

限制 com.richu.UserService 的 sayHello 方法,每客户端并发执行(或占用连接的请求数)不能超过 10 个:

@DubboReference(actives=10, methods = {@Method(name="sayHello",executes=10)})
private UserService userService;

4.4 集群容错模式

Dubbo 内置多种集群容错策略,也可以自行扩展,参见 集群扩展文档。

模式 特点 适用场景
Failover 失败自动切换,重试其它服务器(可用 retries 设置重试次数,不含第一次) 读操作(重试会带来更长延迟)
Failfast 快速失败,只发起一次调用,失败立即报错 非幂等性的写操作,如新增记录
Failsafe 失败安全,出现异常时直接忽略 写入审计日志等操作
Failback 失败自动恢复,后台记录失败请求,定时重发 消息通知操作
Forking 并行调用多个服务器,只要一个成功即返回(可用 forks 设置最大并行数) 实时性要求较高的读操作
Broadcast 广播调用所有提供者,逐个调用,任意一台报错则报错 通知所有提供者更新缓存或日志等本地资源信息

4.4.1 Failover Cluster

失败自动切换,当出现失败,重试其它服务器。通常用于读操作,但重试会带来更长延迟。可通过 retries="2" 来设置重试次数(不含第一次)。

重试次数配置如下:

<dubbo:service retries="2" />

或

<dubbo:reference retries="2" />

或

<dubbo:reference>
    <dubbo:method name="findFoo" retries="2" />
</dubbo:reference>

4.4.2 Failfast Cluster

快速失败,只发起一次调用,失败立即报错。通常用于非幂等性的写操作,比如新增记录。

4.4.3 Failsafe Cluster

失败安全,出现异常时,直接忽略。通常用于写入审计日志等操作。

4.4.4 Failback Cluster

失败自动恢复,后台记录失败请求,定时重发。通常用于消息通知操作。

4.4.5 Forking Cluster

并行调用多个服务器,只要一个成功即返回。通常用于实时性要求较高的读操作,但需要浪费更多服务资源。可通过 forks="2" 来设置最大并行数。

4.4.6 Broadcast Cluster

广播调用所有提供者,逐个调用,任意一台报错则报错。通常用于通知所有提供者更新缓存或日志等本地资源信息。

在广播调用中,可以通过 broadcast.fail.percent 配置节点调用失败的比例,当达到这个比例后,BroadcastClusterInvoker 将不再调用其他节点,直接抛出异常。broadcast.fail.percent 取值在 0~100 范围内。默认情况下当全部调用失败后,才会抛出异常。broadcast.fail.percent 只是控制失败后是否继续调用其他节点,并不改变结果(任意一台报错则报错)。该参数在 dubbo 2.7.10 及以上版本生效。

broadcast.fail.percent=20 代表当 20% 的节点调用失败就抛出异常,不再调用其他节点。

@reference(cluster = "broadcast", parameters = {"broadcast.fail.percent", "20"})
**版本注意** `broadcast.fail.percent` 参数仅在 Dubbo 2.7.10 及以上版本生效,低版本不生效。

一句话总结:Dubbo 通过统一的 RPC 通信与微服务治理能力(服务发现、负载均衡、限流、集群容错等),让分布式微服务之间的远程调用与治理变得简单、可控且可扩展。