快速开始

本文介绍如何使用 Spring Cloud SOFA Registry。

已有项目

如果您已经有 Spring Cloud 项目,且已经接入过其他注册中心(如 Nacos、Consul、Eureka 等),您可以根据接入 Spring Cloud SOFA 的步骤完成公共配置,然后将其他注册中心的依赖替换为 Spring Cloud SOFA Registry。

<!--<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>-->
<dependency>
     <groupId>com.alipay.cloud</groupId>
     <artifactId>spring-cloud-starter-sofa-registry</artifactId>
</dependency>

Spring Cloud SOFA Registry 需要与负载均衡模块配合使用。由于 Spring Cloud SOFA 面向多个版本适配,而不同的 Spring Cloud 版本所支持的负载均衡模块有所不同,因此注册中心模块不会主动引入负载均衡模块,您需要根据您的选择在项目中引入 Ribbon 或 LoadBalancer 的依赖。

以下是 Spring Cloud 版本所支持的负载均衡模块说明:

版本

是否支持 Ribbon

是否支持 LoadBalancer

Greenwich

是(Since SR3)

Hoxton

2020.X

2021.X

手动引入示例:

  • 引入 Ribbon

    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
    </dependency>
  • 引入 LoadBalancer

    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-loadbalancer</artifactId>
    </dependency>
  • 引入 LoadBalancer(Greenwich 版本)

    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-loadbalancer</artifactId>
    </dependency>
重要

在 Spring Cloud 的 Greenwich 和 Hoxton 版本中,同时支持 Ribbon 和 LoadBalancer 两种负载均衡框架,其中Ribbon 是默认的负载均衡框架。如果要在 Greenwich 和 Hoxton 版本中使用 LoadBalancer 框架,必须参考 Spring Cloud 官方文档进行正确配置。

无项目

如果您想从零体验 SOFA 注册中心的接入,可参考以下步骤:

  1. 创建一个 Spring Cloud 项目,在项目工程中添加 Spring Cloud SOFA Registry 依赖和负载均衡依赖。

    说明

    不要配置版本,版本由 dependencyManagement 控制。

    <dependency>
        <groupId>com.alipay.cloud</groupId>
        <artifactId>spring-cloud-starter-sofa-registry</artifactId>
    </dependency>
    <!-- 以 LoadBalancer为例,请根据所使用的 Spring Cloud 版本选择对应的负载均衡器 -->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-loadbalancer</artifactId>
    </dependency>
  2. 在项目的启动类上,通过 EnableDiscoveryClient 注解开启服务发现,通过 EnableFeignClients 注解启用 OpenFeign。

    image.png

  3. 在项目中通过 OpenFeign 或 RestTemplate 对其他服务进行调用。

    此处以 OpenFeign 为例:

    image.png

  4. application.properties文件中配置provider.application.name,指定提供者服务名称。

    image.png

  5. 再创建一个 Spring Cloud 项目作为提供者测试应用,应用的spring.application.name配置为 MySpringCloudProviderApplication,并在启动类上添加EnableDiscoveryClient注解开启服务自动注册,编写 Controller 用于处理请求(此处略)。

  6. 添加必要的公共配置,然后启动应用进行测试。

    公共配置信息请参见 添加公共配置