一、什么是Spring Cloud
Spring Cloud 是基于 Spring Boot 的微服务框架,旨在为开发者提供一系列功能强大的工具和服务,用于构建分布式、可扩展的云原生应用程序。它简化了微服务架构中常见的挑战,如服务发现、配置管理、API 网关、断路器等。
二、Spring cloud 核心组件与功能
1、服务发现与注册(Service Discovery)
-
组件:Nacos(推荐)、Eureka(已停更)、Consul。
-
描述:
-
nacos:Spring Cloud Alibaba中动态服务发现、配置和服务管理的组件,可以理解为服务注册中心和配置中心的组合体。
-
Eureka:Spring Cloud ***flix中的服务治理组件,包含服务注册中心、服务注册与发现机制的实现。
-
Consul:Spring Cloud 中的服务注册中心,用于实现分布式系统的服务发现与配置。
-
2. 配置中心(Configuration Management)
-
组件:Spring Cloud Config + Nacos Config。
-
描述:
-
集中管理配置文件(Git/SVN/数据库存储)。
-
支持动态刷新配置(
@RefreshScope注解)。
-
3. API 网关(API Gateway)
-
组件:Spring Cloud Gateway(主流)、Zuul(旧版)。
-
描述:
-
Gateway:Spring Cloud 中的API网关, 旨在提供一种简单而有效的途径来发送API。
-
Zuul:Spring Cloud ***flix 中的API网关组件,提供了智能路由、访问过滤等功能。
-
4. 客户端负载均衡(Client-Side LB)
-
组件:Spring Cloud LoadBalancer(推荐)、Ribbon(已停更)。
-
描述:
-
Ribbon:Spring Cloud ***flix中的客户端负载均衡组件。
-
5. 服务容错(Fault Tolerance)
-
组件:Resilience4J(推荐)、Hystrix(已停更)。
-
机制:
-
熔断:服务异常时快速失败,防止雪崩。
-
限流:限制请求速率(如令牌桶算法)。
-
重试:失败后自动重试非幂等操作。
-
6. 服务间通信(Service ***munication)
-
同步调用:OpenFeign(声明式 HTTP 客户端) + Spring Cloud LoadBalancer。
-
异步消息:Spring Cloud Stream(绑定 Kafka/RabbitMQ)实现事件驱动。
7. 安全与认证(Security)
-
OAuth2/OpenID Connect:Spring Security 集成 JWT,实现统一鉴权。
-
API 安全:网关层统一校验签名、Token。
四、版本管理
Spring Cloud版本与Spring Boot版本的匹配关系:
| Spring Boot Version | Spring Cloud Alibaba Version | Spring Cloud Version |
|---|---|---|
| 3.0.2 | 2022.0.0.0 | Spring Cloud 2022.0.0 |
| 3.0.2 | 2022.0.0.0-RC2 | Spring Cloud 2022.0.0 |
| 3.0.0 | 2022.0.0.0-RC1 | Spring Cloud 2022.0.0 |
| 2.6.13 | 2021.0.5.0 | Spring Cloud 2021.0.5 |
| 2.6.11 | 2021.0.4.0 | Spring Cloud 2021.0.4 |
| 2.6.3 | 2021.0.1.0 | Spring Cloud 2021.0.1 |
| 2.4.2 | 2021.1 | Spring Cloud 2020.0.1 |
| 2.3.12.RELEASE | 2.2.10-RC1 | Spring Cloud Hoxton.SR12 |
| 2.3.12.RELEASE | 2.2.9.RELEASE | Spring Cloud Hoxton.SR12 |
| 2.3.12.RELEASE | 2.2.8.RELEASE | Spring Cloud Hoxton.SR12 |
| 2.3.12.RELEASE | 2.2.7.RELEASE | Spring Cloud Hoxton.SR12 |
| 2.3.2.RELEASE | 2.2.6.RELEASE | Spring Cloud Hoxton.SR9 |
| 2.2.5.RELEASE | 2.2.1.RELEASE | Spring Cloud Hoxton.SR3 |
| 2.2.X.RELEASE | 2.2.0.RELEASE | Spring Cloud Hoxton.RELEASE |
| 2.1.13.RELEASE | 2.1.4.RELEASE | Spring Cloud Greenwich.SR6 |
| 2.1.X.RELEASE | 2.1.2.RELEASE | Spring Cloud Greenwich |
| 2.0.X.RELEASE | 2.0.4.RELEASE(停止维护,建议升级) | Spring Cloud Finchley |
| 1.5.X.RELEASE | 1.5.1.RELEASE(停止维护,建议升级) | Spring Cloud Edgware |
三、架构原理与执行流程
-
服务注册:服务启动后向 Nacos 注册自身信息。
-
网关路由:客户端请求网关,网关通过服务名路由到目标服务。
-
负载均衡:LoadBalancer 从注册中心拉取实例列表,选择目标实例。
-
服务调用:OpenFeign 发送 HTTP 请求,Resilience4J 监控熔断。