Spring Cloud 基础
Spring Cloud 是在 Spring Boot 之上构建的微服务工具集,提供服务发现、配置、网关、调用、容错、消息、可观测性等能力。它本身不实现具体功能,而是定义抽象接口(SPI),由各厂商/社区提供具体实现。
与 Spring Boot 的关系
Spring Boot
└── 提供自动配置、嵌入容器、起步依赖
Spring Cloud
└── 在 Boot 之上添加分布式系统能力
├── 服务发现(DiscoveryClient)
├── 配置(Environment + RefreshScope)
├── 负载均衡(LoadBalancerClient)
├── 熔断(CircuitBreaker)
└── ...
发行列车
Spring Cloud 使用伦敦地铁站名作为版本代号(按字母顺序递进),与 Spring Boot 版本对应:
| Spring Cloud | Spring Boot | 代号 |
|---|---|---|
| 2023.0.x | 3.2.x | Leyton |
| 2022.0.x | 3.0.x / 3.1.x | Kilburn |
| 2021.0.x | 2.6.x / 2.7.x | Jubilee |
| Hoxton | 2.2.x / 2.3.x | — |
Spring Cloud Alibaba 有独立版本线,需与上表对应的 Spring Boot 版本匹配,见官方兼容矩阵。
核心抽象与实现
| 抽象接口 | 官方实现 | Alibaba 实现 |
|---|---|---|
DiscoveryClient 服务发现 | Eureka | Nacos Discovery |
Environment 配置中心 | Config Server | Nacos Config |
LoadBalancerClient 负载均衡 | Spring Cloud LoadBalancer | — |
CircuitBreaker 熔断 | Resilience4j | Sentinel |
GatewayFilter 网关过滤 | Spring Cloud Gateway | — |
Binder 消息绑定 | RabbitMQ / Kafka Binder | RocketMQ Binder |
BOM 依赖管理
<dependencyManagement>
<dependencies>
<!-- Spring Cloud -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>2023.0.3</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!-- Spring Cloud Alibaba -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>2023.0.1.2</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>微服务拆分原则
| 原则 | 说明 |
|---|---|
| 单一职责 | 每个服务只负责一个业务域 |
| 高内聚低耦合 | 服务内部改动不影响其他服务 |
| 围绕业务能力 | 按业务边界拆,而不是技术层 |
| 数据库独立 | 每个服务有自己的数据库,不共享 Schema |
| API 契约稳定 | 通过接口版本化管理演化 |
服务通信模式
同步调用
├── OpenFeign(HTTP/REST,声明式)
├── WebClient(响应式 HTTP)
└── gRPC(高性能,强类型)
异步解耦
├── Spring Cloud Stream(统一 Binder 抽象)
└── 直接使用 MQ SDK(Kafka / RabbitMQ / RocketMQ)
本地调试多服务
方式一:多 IDE 实例
每个服务独立运行,修改端口互不冲突:
server:
port: 8081 # 各服务不同端口
spring:
application:
name: order-service方式二:Docker Compose
services:
nacos:
image: nacos/nacos-server:v2.3.0
ports: ["8848:8848"]
order-service:
build: ./order-service
environment:
NACOS_SERVER: nacos:8848
user-service:
build: ./user-service
environment:
NACOS_SERVER: nacos:8848常见陷阱
| 陷阱 | 说明 |
|---|---|
| 版本不匹配 | Spring Boot / Cloud / Alibaba 三者版本必须对照兼容矩阵 |
| 注册中心未就绪 | 服务启动顺序:注册中心 → 配置中心 → 业务服务 |
| Feign 超时默认极短 | 默认 1s/5s,生产必须手动配置 |
| 本地 IP 注册错误 | 多网卡环境需 spring.cloud.inetutils.preferred-networks 指定网段 |
| 配置刷新未生效 | @RefreshScope 的 Bean 才能热刷新 |