Spring Cloud 详细讲解:项目使用、适用范围、落地方案与资源文档

更新时间:2026-06-26
说明:Spring Cloud 常被误写成 Spring Clound,正确名称是 Spring Cloud
适合人群:Java / Spring Boot 初学者、准备做微服务项目的后端开发、需要理解企业级分布式系统的开发者。


目录

  1. Spring Cloud 是什么
  2. Spring Boot、Spring Cloud、Spring Cloud Alibaba 的关系
  3. Spring Cloud 解决什么问题
  4. 适用范围:什么时候适合用 Spring Cloud
  5. 不适用范围:什么时候不建议上微服务
  6. 核心架构思想
  7. 核心组件详细讲解
  8. 官方体系与国内常用体系对比
  9. 项目中怎么使用 Spring Cloud
  10. 商城/图书管理系统微服务项目示例
  11. 项目模块拆分建议
  12. 环境准备与版本选择
  13. Maven 依赖配置示例
  14. Nacos 注册中心与配置中心示例
  15. Gateway 网关示例
  16. OpenFeign 服务调用示例
  17. 负载均衡、熔断、限流、降级
  18. 统一认证授权方案
  19. 数据库与分布式事务
  20. 消息队列与异步处理
  21. 日志、链路追踪与监控
  22. 部署方案:本地、服务器、Docker、Kubernetes
  23. 开发规范与目录结构
  24. 常见问题与解决方案
  25. 学习路线
  26. 面试常问问题
  27. 官方资源与学习文档链接

1. Spring Cloud 是什么

Spring Cloud 是 Spring 生态下的一套分布式系统开发工具集,它不是一个单独的框架,而是一组用于构建微服务系统的组件集合。

它主要帮助开发者快速处理微服务系统中的通用问题,例如:

  • 服务注册与发现
  • 配置中心
  • API 网关
  • 服务间调用
  • 负载均衡
  • 熔断降级
  • 限流
  • 消息驱动
  • 分布式配置刷新
  • 分布式链路追踪
  • 微服务部署与治理

简单理解:

Spring Boot:快速开发一个单体服务 / 一个后端应用
Spring Cloud:把多个 Spring Boot 服务组织成一套微服务系统
Spring Cloud Alibaba:面向国内常用中间件的一套 Spring Cloud 扩展方案

2. Spring Boot、Spring Cloud、Spring Cloud Alibaba 的关系

2.1 Spring Boot

Spring Boot 负责让你快速开发一个独立可运行的 Java Web 应用。

它解决的是:

  • 快速创建项目
  • 自动配置
  • 内嵌 Tomcat
  • 简化 Maven 依赖
  • 快速整合 MySQL、Redis、MyBatis、Spring Security 等

常见项目:

一个图书管理系统后端
一个商城后台接口
一个后台管理系统接口
一个博客系统接口

2.2 Spring Cloud

Spring Cloud 负责把多个 Spring Boot 服务组合起来。

例如商城系统可以拆成:

用户服务 user-service
商品服务 product-service
订单服务 order-service
支付服务 payment-service
库存服务 stock-service
文件服务 file-service
后台管理 admin-service
网关服务 gateway-service
认证服务 auth-service

这些服务之间需要互相调用、注册、发现、鉴权、限流、监控,这些就是 Spring Cloud 要解决的问题。

2.3 Spring Cloud Alibaba

Spring Cloud Alibaba 是 Alibaba 维护的一套微服务解决方案,常用于国内项目。

常见组件:

  • Nacos:注册中心 + 配置中心
  • Sentinel:流量控制、熔断、降级
  • Seata:分布式事务
  • RocketMQ:消息队列
  • Dubbo:RPC 通信

国内中小型项目常用组合:

Spring Boot + Spring Cloud Alibaba + Nacos + Gateway + OpenFeign + Sentinel + MyBatis-Plus + MySQL + Redis

3. Spring Cloud 解决什么问题

3.1 服务太多,不知道地址

单体项目里所有代码在一个应用里,不需要服务发现。

微服务后,每个服务都有自己的 IP、端口、实例数量:

user-service: 192.168.1.10:8081
user-service: 192.168.1.11:8081
order-service: 192.168.1.12:8082
product-service: 192.168.1.13:8083

服务地址会变,实例会扩容缩容,如果手写 IP 地址会很难维护。

解决方案:

注册中心:Nacos / Eureka / Consul / Zookeeper

3.2 服务之间怎么调用

订单服务需要查用户信息、商品信息、库存信息:

order-service -> user-service
order-service -> product-service
order-service -> stock-service

如果直接用 RestTemplate 拼 URL,代码不优雅,维护困难。

解决方案:

OpenFeign:像调用本地接口一样调用远程服务

3.3 服务挂了怎么办

订单服务调用支付服务,如果支付服务卡住,订单服务线程也可能被拖死,最后导致整个系统雪崩。

解决方案:

熔断:服务异常达到阈值后,短时间内不再调用
降级:返回兜底数据或友好提示
限流:限制瞬时请求量,保护系统
隔离:避免一个接口拖垮整个服务

常见组件:

  • Spring Cloud CircuitBreaker
  • Resilience4j
  • Sentinel

3.4 外部请求怎么统一进入系统

前端不应该直接访问每个微服务:

/user/list
/product/list
/order/create
/payment/pay

如果直接暴露所有服务,会出现:

  • 接口地址混乱
  • 鉴权重复
  • 跨域配置重复
  • 日志统计困难
  • 限流不好做
  • 服务暴露风险高

解决方案:

API Gateway:统一入口、路由转发、鉴权、跨域、限流、日志

常用组件:

Spring Cloud Gateway

3.5 配置怎么统一管理

不同环境有不同配置:

开发环境 dev
测试环境 test
生产环境 prod

每个服务都有数据库、Redis、MQ、日志级别、第三方接口配置,如果写在每个服务本地,修改起来非常麻烦。

解决方案:

配置中心:Spring Cloud Config / Nacos Config

4. 适用范围:什么时候适合用 Spring Cloud

Spring Cloud 适合以下场景。

4.1 中大型业务系统

例如:

  • 电商商城
  • 外卖平台
  • 酒店预订系统
  • 医院预约系统
  • 在线教育平台
  • SaaS 系统
  • ERP / CRM / OA 系统
  • 多端应用后端:PC、移动端、小程序、App、后台管理系统

4.2 团队多人协作

当后端团队人数较多时,不同小组可以负责不同服务:

用户组:user-service
商品组:product-service
订单组:order-service
支付组:payment-service
运维组:gateway、监控、部署

这样可以减少代码冲突,提高并行开发效率。

4.3 服务需要独立扩容

比如商城中商品浏览量很高,但是支付请求相对少。

可以单独扩容商品服务:

product-service x 5
order-service x 2
payment-service x 2
user-service x 3

这比整个单体应用一起扩容更灵活。

4.4 需要高可用

如果系统要求:

  • 服务挂了不能影响全部功能
  • 某些服务需要多实例部署
  • 系统要支持限流、熔断、降级
  • 线上要有监控与日志追踪

Spring Cloud 会更适合。

4.5 需要多系统集成

例如:

  • 后台管理系统
  • 前台商城系统
  • 会员系统
  • 支付系统
  • 短信系统
  • 文件上传系统
  • 第三方物流系统
  • 数据统计系统

这类系统天然适合服务拆分。


5. 不适用范围:什么时候不建议上微服务

以下情况不建议一开始就上 Spring Cloud。

5.1 小项目、练手项目

例如:

  • 简单博客
  • 简单图书管理系统
  • 简单公司官网后台
  • 小型展示站接口
  • 单人开发的小系统

建议先用:

Spring Boot 单体项目 + MySQL + Redis + Vue3

等业务复杂后再拆微服务。

5.2 团队运维能力不足

微服务不是只拆代码,还要处理:

  • 注册中心
  • 配置中心
  • 网关
  • 服务部署
  • 日志采集
  • 监控告警
  • 链路追踪
  • 数据一致性
  • 分布式事务
  • 服务版本管理

如果没有足够经验,系统复杂度会明显上升。

5.3 数据库关系非常紧密

如果所有功能都强依赖同一个数据库、同一批表,而且事务很多,强行拆服务会导致分布式事务复杂度变高。

5.4 业务还没稳定

业务经常变化时,不建议过早拆太细。

推荐顺序:

先单体开发 -> 模块化设计 -> 业务稳定 -> 拆成微服务

6. 核心架构思想

Spring Cloud 项目通常采用这样的结构:

前端 Vue3 / React / 小程序 / App
        |
        v
API Gateway 网关
        |
        v
认证鉴权 Auth Service
        |
        v
业务微服务集群
  |---------- user-service
  |---------- product-service
  |---------- order-service
  |---------- payment-service
  |---------- file-service
  |---------- admin-service
        |
        v
基础设施
  |---------- 注册中心 Nacos / Eureka / Consul
  |---------- 配置中心 Nacos Config / Spring Cloud Config
  |---------- MySQL
  |---------- Redis
  |---------- MQ:RabbitMQ / Kafka / RocketMQ
  |---------- 日志:ELK / Loki
  |---------- 监控:Prometheus + Grafana

核心思想:

1. 所有服务独立启动
2. 所有服务注册到注册中心
3. 网关统一接收外部请求
4. 网关根据路由规则转发到具体服务
5. 服务之间通过 OpenFeign 调用
6. 配置由配置中心统一管理
7. 服务异常时通过熔断降级保护系统
8. 日志、监控、链路追踪用于排查问题

7. 核心组件详细讲解

7.1 注册中心:Service Discovery

作用:管理所有服务实例。

常见组件:

组件说明使用建议
EurekaNetflix 体系,早期 Spring Cloud 常用老项目维护可以学
Nacos Discovery阿里体系,国内项目常用新项目推荐
Consul支持服务发现、KV 配置、健康检查云原生项目可选
Zookeeper早期分布式协调组件了解即可

注册中心解决的问题:

服务在哪里?
服务有没有挂?
服务有几个实例?
调用时应该请求哪个实例?

7.2 配置中心:Config Center

作用:统一管理配置。

常见配置:

数据库地址
Redis 地址
MQ 地址
日志级别
上传文件地址
第三方接口 Key
短信配置
支付配置
不同环境配置

常见组件:

组件说明使用建议
Spring Cloud Config官方配置中心,常配 Git 仓库官方体系可用
Nacos Config配置中心 + 注册中心合一国内项目推荐
Apollo携程开源配置中心企业项目也常见

7.3 API 网关:Spring Cloud Gateway

网关是微服务系统的统一入口。

核心功能:

  • 路由转发
  • 统一跨域
  • 统一鉴权
  • 统一日志
  • 统一限流
  • 黑白名单
  • 请求头处理
  • 灰度发布
  • 请求路径重写

请求流程:

浏览器 / App / 小程序
        |
        v
Spring Cloud Gateway
        |
        v
具体微服务

示例:

/api/user/**    -> user-service
/api/order/**   -> order-service
/api/product/** -> product-service

7.4 服务调用:OpenFeign

OpenFeign 让服务间调用像调用本地接口一样简单。

不用 Feign 时:

String url = "http://user-service/user/1";
User user = restTemplate.getForObject(url, User.class);

使用 Feign 后:

@FeignClient(name = "user-service")
public interface UserClient {
    @GetMapping("/user/{id}")
    UserDTO getById(@PathVariable("id") Long id);
}

调用:

UserDTO user = userClient.getById(1L);

优点:

  • 代码更清晰
  • 方便统一拦截请求头
  • 可以集成负载均衡
  • 可以结合熔断降级

7.5 负载均衡:Spring Cloud LoadBalancer

当一个服务有多个实例时,需要选择一个实例处理请求。

例如:

user-service 实例 1:8081
user-service 实例 2:8082
user-service 实例 3:8083

负载均衡策略:

  • 轮询
  • 随机
  • 权重
  • 按区域
  • 按响应时间

Spring Cloud 官方现在主要使用 Spring Cloud LoadBalancer。


7.6 熔断降级:Circuit Breaker

作用:防止服务雪崩。

常见场景:

订单服务调用支付服务
支付服务超时
订单服务大量线程阻塞
订单服务也被拖垮
最终整套系统不可用

熔断后:

一段时间内不再调用异常服务
直接走 fallback 降级逻辑
等待恢复后再尝试放行

常见组件:

  • Spring Cloud CircuitBreaker
  • Resilience4j
  • Sentinel

7.7 限流:Rate Limit

作用:限制请求数量,保护服务。

常见限流维度:

  • 按 IP 限流
  • 按用户限流
  • 按接口限流
  • 按服务限流
  • 按 QPS 限流
  • 按秒杀活动限流

常见工具:

  • Sentinel
  • Redis + Lua
  • Gateway RateLimiter
  • Nginx 限流

7.8 Spring Cloud Bus

Spring Cloud Bus 用于把分布式系统中的节点连接起来,常用于配置刷新。

典型场景:

配置中心修改配置
通过消息队列广播变更事件
多个服务自动刷新配置

常用消息中间件:

  • RabbitMQ
  • Kafka

7.9 Spring Cloud Stream

Spring Cloud Stream 用于构建消息驱动微服务。

它把消息队列抽象成 Binder,开发者不用直接关心底层 MQ 的细节。

常见底层中间件:

  • RabbitMQ
  • Kafka
  • RocketMQ(通常通过 Alibaba 生态使用)

适合场景:

  • 订单创建后异步扣库存
  • 支付成功后发送通知
  • 用户注册后发送短信
  • 日志采集
  • 数据同步

7.10 Spring Cloud Kubernetes

如果项目部署到 Kubernetes,可以使用 Spring Cloud Kubernetes 获取服务发现、配置、密钥等能力。

适合:

  • 容器化部署
  • K8s 集群
  • 云原生架构
  • 大型微服务系统

8. 官方体系与国内常用体系对比

8.1 官方 Spring Cloud 体系

功能组件
注册中心Eureka / Consul / Zookeeper / Kubernetes
配置中心Spring Cloud Config
网关Spring Cloud Gateway
服务调用OpenFeign
负载均衡Spring Cloud LoadBalancer
熔断Spring Cloud CircuitBreaker + Resilience4j
消息驱动Spring Cloud Stream
配置广播Spring Cloud Bus

适合:

  • 学习官方标准体系
  • 海外项目
  • 云原生项目
  • 想深入理解 Spring Cloud 原生组件

8.2 国内常用 Spring Cloud Alibaba 体系

功能组件
注册中心Nacos Discovery
配置中心Nacos Config
网关Spring Cloud Gateway
服务调用OpenFeign
负载均衡Spring Cloud LoadBalancer
限流熔断Sentinel
分布式事务Seata
消息队列RocketMQ / RabbitMQ / Kafka

适合:

  • 国内企业项目
  • 阿里云部署
  • 需要 Nacos 控制台
  • 希望注册中心和配置中心合一
  • 需要 Sentinel 可视化限流熔断

9. 项目中怎么使用 Spring Cloud

9.1 推荐使用步骤

第 1 步:先把单体 Spring Boot 项目跑通
第 2 步:拆分公共模块 common
第 3 步:拆分用户服务 user-service
第 4 步:拆分业务服务 product/order/payment 等
第 5 步:引入注册中心 Nacos
第 6 步:引入配置中心 Nacos Config
第 7 步:引入 Gateway 网关
第 8 步:服务间用 OpenFeign 调用
第 9 步:加入 Redis、MQ、限流熔断
第 10 步:加入监控、日志、链路追踪
第 11 步:Docker 部署
第 12 步:线上 Nginx + 网关 + 多服务部署

9.2 不建议一开始拆太细

错误做法:

刚开始就拆 20 个服务
每个服务只有几个接口
部署复杂度暴增
调试困难
数据库事务复杂

推荐做法:

先按业务边界粗拆
后期根据访问量和团队分工再细拆

10. 商城/图书管理系统微服务项目示例

10.1 如果是简单图书管理系统

建议不要直接上完整 Spring Cloud。

推荐:

前端:Vue3 + Element Plus
后端:Spring Boot
数据库:MySQL
缓存:Redis 可选
部署:Nginx + Spring Boot Jar

适合模块:

登录注册
用户管理
图书管理
分类管理
借阅管理
归还管理
逾期管理
公告管理
后台管理

10.2 如果是大型图书馆/校园平台

可以使用 Spring Cloud。

推荐拆分:

gateway-service        网关服务
auth-service           认证服务
user-service           用户服务
book-service           图书服务
borrow-service         借阅服务
message-service        消息通知服务
file-service           文件服务
admin-service          后台管理服务
search-service         搜索服务

10.3 如果是商品售卖官网/商城系统

Spring Cloud 更适合。

推荐拆分:

mall-gateway           网关服务
mall-auth              认证服务
mall-user              用户服务
mall-product           商品服务
mall-order             订单服务
mall-cart              购物车服务
mall-payment           支付服务
mall-stock             库存服务
mall-coupon            优惠券服务
mall-file              文件服务
mall-admin             后台管理服务
mall-search            搜索服务
mall-message           消息通知服务
mall-common            公共模块

11. 项目模块拆分建议

11.1 标准 Maven 多模块结构

mall-cloud
├── mall-common                 公共模块
│   ├── common-core             通用工具、统一返回、异常处理
│   ├── common-redis            Redis 工具
│   ├── common-security         安全认证工具
│   └── common-feign            Feign 公共配置
│
├── mall-gateway                网关服务
├── mall-auth                   认证服务
├── mall-user                   用户服务
├── mall-product                商品服务
├── mall-order                  订单服务
├── mall-payment                支付服务
├── mall-file                   文件服务
├── mall-admin                  后台管理服务
└── pom.xml

11.2 单个服务目录结构

mall-user
├── src/main/java/com/example/user
│   ├── controller              控制器层
│   ├── service                 业务接口
│   ├── service/impl            业务实现
│   ├── mapper                  MyBatis Mapper
│   ├── entity                  数据库实体
│   ├── dto                     请求/传输对象
│   ├── vo                      返回视图对象
│   ├── client                  Feign 客户端
│   ├── config                  配置类
│   └── UserApplication.java    启动类
│
└── src/main/resources
    ├── application.yml
    └── mapper/*.xml

12. 环境准备与版本选择

12.1 必备环境

工具建议版本作用
JDK17 / 21 / 25,具体看 Spring Boot 版本Java 运行环境
Maven3.9+项目依赖管理
MySQL8.0+数据库
Redis7.x+缓存、验证码、限流辅助
Nacos2.x / 3.x,按项目兼容性选择注册中心、配置中心
IDEAIntelliJ IDEAJava 开发工具
Postman / Apifox最新版接口测试
Git最新版版本管理

12.2 版本选择原则

Spring Cloud 必须和 Spring Boot 版本匹配。

推荐原则:

不要随便混用 Spring Boot 和 Spring Cloud 版本
先确定 Spring Boot 版本
再查看 Spring Cloud 官方兼容表
再确定 Spring Cloud Alibaba 版本

常见选择:

稳定学习/企业项目:Spring Boot 3.5.x + Spring Cloud 2025.0.x + Spring Cloud Alibaba 2025.0.x
尝鲜新版本:Spring Boot 4.0.x + Spring Cloud 2025.1.x + Spring Cloud Alibaba 2025.1.x
国内 Nacos 项目:必须再匹配 Spring Cloud Alibaba 对应版本

13. Maven 依赖配置示例

13.1 父工程 pom.xml 示例

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>mall-cloud</artifactId>
    <version>1.0.0</version>
    <packaging>pom</packaging>

    <properties>
        <java.version>17</java.version>
        <spring-boot.version>3.5.0</spring-boot.version>
        <spring-cloud.version>2025.0.0</spring-cloud.version>
        <spring-cloud-alibaba.version>2025.0.0.0</spring-cloud-alibaba.version>
    </properties>

    <dependencyManagement>
        <dependencies>
            <!-- Spring Boot 依赖管理 -->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>${spring-boot.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>

            <!-- Spring Cloud 依赖管理 -->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>

            <!-- Spring Cloud Alibaba 依赖管理 -->
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>${spring-cloud-alibaba.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <modules>
        <module>mall-common</module>
        <module>mall-gateway</module>
        <module>mall-auth</module>
        <module>mall-user</module>
        <module>mall-product</module>
        <module>mall-order</module>
    </modules>
</project>

注意:上面的版本只是示例,实际项目要以官方兼容表、Maven Central 和项目脚手架生成为准。


14. Nacos 注册中心与配置中心示例

14.1 添加依赖

<dependencies>
    <!-- Nacos 服务发现 -->
    <dependency>
        <groupId>com.alibaba.cloud</groupId>
        <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
    </dependency>

    <!-- Nacos 配置中心 -->
    <dependency>
        <groupId>com.alibaba.cloud</groupId>
        <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
    </dependency>
</dependencies>

14.2 application.yml 示例

server:
  port: 8081

spring:
  application:
    name: mall-user
  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848
      config:
        server-addr: 127.0.0.1:8848
        file-extension: yaml
        namespace: dev
        group: DEFAULT_GROUP

14.3 启动类

package com.example.user;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class UserApplication {
    public static void main(String[] args) {
        SpringApplication.run(UserApplication.class, args);
    }
}

14.4 Nacos 配置命名建议

mall-user-dev.yaml
mall-user-test.yaml
mall-user-prod.yaml
mall-order-dev.yaml
mall-product-dev.yaml

15. Gateway 网关示例

15.1 网关依赖

<dependencies>
    <!-- Spring Boot 3.x / Spring Cloud 2025.0.x 常用写法 -->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-gateway</artifactId>
    </dependency>

    <!-- 如果使用 Spring Boot 4.x / Spring Cloud Gateway 5.x,可按官方文档选择 server-webflux 或 server-webmvc starter -->

    <dependency>
        <groupId>com.alibaba.cloud</groupId>
        <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
    </dependency>
</dependencies>

15.2 网关 application.yml

server:
  port: 8080

spring:
  application:
    name: mall-gateway
  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848
    gateway:
      routes:
        - id: user-service
          uri: lb://mall-user
          predicates:
            - Path=/api/user/**
          filters:
            - StripPrefix=1

        - id: product-service
          uri: lb://mall-product
          predicates:
            - Path=/api/product/**
          filters:
            - StripPrefix=1

        - id: order-service
          uri: lb://mall-order
          predicates:
            - Path=/api/order/**
          filters:
            - StripPrefix=1

lb://mall-user 表示从注册中心寻找 mall-user 服务,并进行负载均衡。

15.3 网关跨域配置示例

package com.example.gateway.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;

@Configuration
public class CorsConfig {

    @Bean
    public CorsWebFilter corsWebFilter() {
        CorsConfiguration config = new CorsConfiguration();
        config.addAllowedOriginPattern("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        config.setAllowCredentials(true);

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        return new CorsWebFilter(source);
    }
}

16. OpenFeign 服务调用示例

16.1 添加依赖

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

16.2 启动类开启 Feign

package com.example.order;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;

@EnableFeignClients
@SpringBootApplication
public class OrderApplication {
    public static void main(String[] args) {
        SpringApplication.run(OrderApplication.class, args);
    }
}

16.3 定义 Feign 客户端

package com.example.order.client;

import com.example.common.result.R;
import com.example.order.dto.UserDTO;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

@FeignClient(name = "mall-user", path = "/user")
public interface UserClient {

    @GetMapping("/{id}")
    R<UserDTO> getUserById(@PathVariable("id") Long id);
}

16.4 在业务中调用

package com.example.order.service.impl;

import com.example.order.client.UserClient;
import com.example.order.dto.UserDTO;
import org.springframework.stereotype.Service;

@Service
public class OrderServiceImpl {

    private final UserClient userClient;

    public OrderServiceImpl(UserClient userClient) {
        this.userClient = userClient;
    }

    public void createOrder(Long userId) {
        UserDTO user = userClient.getUserById(userId).getData();
        // 校验用户、创建订单、扣库存、发送消息等
    }
}

17. 负载均衡、熔断、限流、降级

17.1 负载均衡

多个服务实例注册到 Nacos 后,OpenFeign 或 Gateway 可以通过服务名调用。

mall-user 实例 1:8081
mall-user 实例 2:8082
mall-user 实例 3:8083

请求会分配到不同实例,提高并发能力。

17.2 熔断

例如订单服务调用支付服务,如果支付服务异常,就不要一直等待。

伪逻辑:

正常:order -> payment -> success
异常:order -> payment timeout -> fallback
熔断:短时间内直接 fallback,不继续请求 payment
恢复:payment 正常后逐步放开请求

17.3 降级

降级返回兜底结果。

示例:

public PaymentResult fallbackPay(Long orderId) {
    return PaymentResult.fail("支付系统繁忙,请稍后再试");
}

17.4 限流

常见限流规则:

登录接口:同 IP 每分钟最多 10 次
短信接口:同手机号每分钟 1 次
秒杀接口:总 QPS 限制 1000
上传接口:单用户每分钟最多 20 次

18. 统一认证授权方案

18.1 推荐方案

Spring Security + JWT + Gateway 全局过滤器 + Redis

流程:

1. 用户登录 auth-service
2. auth-service 校验账号密码
3. 生成 JWT token
4. 前端保存 token
5. 请求时带上 Authorization 请求头
6. Gateway 校验 token
7. Gateway 把用户 ID、角色、权限放到请求头
8. 后端服务读取用户信息

18.2 网关鉴权逻辑

白名单接口直接放行:/login、/register、/captcha
其他接口校验 token
token 无效返回 401
权限不足返回 403

18.3 后台管理权限设计

推荐 RBAC:

用户 user
角色 role
菜单 menu
权限 permission
用户角色关系 user_role
角色权限关系 role_permission

19. 数据库与分布式事务

19.1 数据库拆分方式

方式一:共享数据库
所有服务连接同一个 MySQL

优点:

  • 简单
  • 适合初学和中小项目
  • 查询方便

缺点:

  • 服务之间数据库耦合高
  • 不是真正彻底微服务
方式二:每个服务独立数据库
mall-user     -> mall_user_db
mall-product  -> mall_product_db
mall-order    -> mall_order_db
mall-payment  -> mall_payment_db

优点:

  • 服务边界清晰
  • 独立扩展
  • 更符合微服务思想

缺点:

  • 跨库事务复杂
  • 查询复杂
  • 运维成本高

19.2 分布式事务处理方式

常见方案:

方案说明适合场景
本地事务单服务单数据库事务简单业务
TCCTry / Confirm / Cancel强一致要求较高
Saga长事务拆分为多个步骤业务流程长
MQ 最终一致通过消息队列保证最终成功电商常用
Seata阿里生态分布式事务组件国内项目常用

推荐:

能不用分布式事务就不用
能通过业务补偿解决就不要强行追求强一致
订单、库存、支付建议使用最终一致性设计

20. 消息队列与异步处理

20.1 为什么使用 MQ

同步调用问题:

下单 -> 扣库存 -> 支付 -> 发短信 -> 发邮件 -> 生成积分

如果全部同步执行,接口会很慢。

使用 MQ:

下单成功 -> 发送订单创建消息
库存服务消费消息扣库存
消息服务消费消息发短信
积分服务消费消息加积分

优点:

  • 解耦
  • 削峰
  • 异步
  • 提高响应速度
  • 支持最终一致性

20.2 常见 MQ 选择

MQ特点使用建议
RabbitMQ简单稳定,适合业务消息中小项目推荐
Kafka高吞吐,适合日志和大数据大流量场景
RocketMQ阿里生态,事务消息能力强国内电商/金融场景

21. 日志、链路追踪与监控

21.1 为什么需要链路追踪

微服务调用链很长:

gateway -> order-service -> user-service -> product-service -> stock-service -> payment-service

如果一个请求慢了,需要知道慢在哪里。

21.2 常见方案

功能工具
日志收集ELK / EFK / Loki
指标监控Prometheus + Grafana
应用监控Spring Boot Actuator
链路追踪Micrometer Tracing / Zipkin / SkyWalking
告警Alertmanager

21.3 日志字段建议

timestamp
traceId
spanId
serviceName
userId
requestUri
httpMethod
statusCode
costTime
errorMessage

22. 部署方案:本地、服务器、Docker、Kubernetes

22.1 本地开发启动顺序

1. 启动 MySQL
2. 启动 Redis
3. 启动 Nacos
4. 启动 Gateway
5. 启动 Auth Service
6. 启动 User Service
7. 启动 Product Service
8. 启动 Order Service
9. 启动前端 Vue3

22.2 服务器部署方案

适合阿里云 + 宝塔:

Nginx:部署前端静态文件、反向代理网关
Java:运行各个 Spring Boot Jar
MySQL:数据库
Redis:缓存
Nacos:注册中心和配置中心

访问流程:

浏览器 -> Nginx -> Gateway -> 微服务 -> MySQL/Redis/MQ

22.3 Docker Compose 部署

适合学习和中小项目。

服务:

mysql
redis
nacos
gateway
user-service
product-service
order-service

22.4 Kubernetes 部署

适合大型项目。

常见资源:

Deployment
Service
Ingress
ConfigMap
Secret
HorizontalPodAutoscaler

23. 开发规范与目录结构

23.1 接口返回统一格式

public class R<T> {
    private Integer code;
    private String message;
    private T data;

    public static <T> R<T> ok(T data) {
        R<T> r = new R<>();
        r.code = 200;
        r.message = "success";
        r.data = data;
        return r;
    }

    public static <T> R<T> fail(String message) {
        R<T> r = new R<>();
        r.code = 500;
        r.message = message;
        return r;
    }
}

23.2 异常统一处理

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public R<Void> handleException(Exception e) {
        return R.fail(e.getMessage());
    }
}

23.3 DTO、VO、Entity 区分

Entity:数据库表对应对象
DTO:接口请求参数或服务间传输对象
VO:返回给前端展示的对象

23.4 命名规范

服务名:mall-user、mall-order、mall-product
包名:com.example.mall.user
接口路径:/user/list、/order/create
数据库表:sys_user、mall_order、mall_product
配置文件:mall-user-dev.yaml

24. 常见问题与解决方案

24.1 服务注册不到 Nacos

检查:

1. Nacos 是否启动
2. server-addr 是否正确
3. 服务名 spring.application.name 是否配置
4. 依赖是否引入 nacos-discovery
5. Nacos 命名空间 namespace 是否一致
6. 防火墙端口是否开放

24.2 Gateway 转发失败

检查:

1. 路由 Path 是否正确
2. uri 是否使用 lb://服务名
3. 服务是否已注册到 Nacos
4. StripPrefix 是否配置正确
5. 网关依赖是否使用 WebFlux 版本

24.3 Feign 调用失败

检查:

1. 是否添加 @EnableFeignClients
2. @FeignClient name 是否等于注册中心服务名
3. 路径 path 是否正确
4. 参数注解是否完整,例如 @PathVariable("id")
5. 返回对象是否能正常序列化

24.4 版本冲突

解决:

1. 使用 Spring Boot BOM
2. 使用 Spring Cloud BOM
3. 使用 Spring Cloud Alibaba BOM
4. 不要手动乱写组件版本
5. 查看官方兼容表
6. 用 mvn dependency:tree 排查冲突

24.5 前端跨域问题

建议:

开发环境:Vite proxy 转发到 Gateway
生产环境:Nginx 反向代理到 Gateway
后端:Gateway 统一配置 CORS
不要每个微服务都单独处理跨域

25. 学习路线

第一阶段:Spring Boot 基础

必须掌握:

  • Spring Boot 项目创建
  • Controller / Service / Mapper
  • MyBatis-Plus
  • MySQL CRUD
  • Redis 基础
  • 统一返回
  • 统一异常
  • 登录注册
  • JWT
  • Spring Security 基础

第二阶段:微服务基础

学习:

  • 微服务概念
  • 服务拆分原则
  • 注册中心
  • 配置中心
  • 网关
  • OpenFeign
  • 负载均衡

第三阶段:服务治理

学习:

  • 熔断
  • 降级
  • 限流
  • Sentinel
  • Resilience4j
  • Gateway 过滤器
  • 链路追踪
  • 监控告警

第四阶段:分布式能力

学习:

  • Redis 分布式锁
  • MQ 异步解耦
  • 分布式事务
  • Seata
  • 接口幂等
  • 数据一致性
  • 缓存一致性

第五阶段:部署上线

学习:

  • Linux
  • Nginx
  • Docker
  • Docker Compose
  • Jenkins / GitHub Actions
  • 阿里云 ECS
  • 宝塔面板
  • Kubernetes 基础

26. 面试常问问题

26.1 Spring Cloud 是什么?

Spring Cloud 是 Spring 生态中的分布式系统开发工具集,主要用于构建微服务系统。它提供注册中心、配置中心、网关、服务调用、负载均衡、熔断降级、消息驱动等能力,帮助多个 Spring Boot 服务协同工作。

26.2 Spring Boot 和 Spring Cloud 的区别?

Spring Boot 用于快速开发单个应用,解决自动配置、依赖管理、应用启动等问题。Spring Cloud 用于管理多个 Spring Boot 服务之间的关系,解决服务发现、远程调用、网关、配置中心、熔断降级等分布式问题。

26.3 为什么需要注册中心?

微服务部署后,每个服务可能有多个实例,IP 和端口可能变化。注册中心用于维护服务实例列表,调用方只需要通过服务名访问,不需要写死 IP 和端口。

26.4 Gateway 的作用是什么?

Gateway 是微服务系统的统一入口,负责路由转发、统一鉴权、跨域、限流、日志、黑白名单、请求头处理等。

26.5 OpenFeign 的作用是什么?

OpenFeign 是声明式 HTTP 客户端,可以让服务间调用像调用本地接口一样简单,并且可以集成服务发现、负载均衡、熔断降级等能力。

26.6 熔断和降级有什么区别?

熔断是当服务异常达到阈值后,暂时停止调用该服务,避免故障扩散。降级是在服务不可用或压力过大时,返回兜底结果或简化功能,保证核心流程可用。

26.7 Nacos 和 Eureka 有什么区别?

Eureka 主要用于服务注册与发现;Nacos 同时支持服务注册发现和配置管理,还提供控制台,国内项目使用较多。

26.8 什么是服务雪崩?

当一个服务异常导致调用它的服务也被拖垮,故障继续向上游扩散,最终导致大面积服务不可用,这就是服务雪崩。

26.9 微服务一定要一个服务一个数据库吗?

严格微服务推荐一个服务管理自己的数据,但实际中小项目可以先共享数据库。是否拆库要看业务复杂度、团队能力、事务边界和运维能力。

26.10 Spring Cloud 项目怎么部署?

常见方式是 Nginx 部署前端并反向代理到 Gateway,Gateway 再转发到各个微服务。后端服务可以用 Jar、Docker Compose 或 Kubernetes 部署,同时需要 MySQL、Redis、Nacos、MQ 等基础设施。


27. 官方资源与学习文档链接

27.1 Spring 官方资源

名称链接
Spring 官网https://spring.io/
Spring Cloud 项目页https://spring.io/projects/spring-cloud
Spring Cloud Reference Docshttps://docs.spring.io/spring-cloud-release/reference/index.html
Spring Boot 官网https://spring.io/projects/spring-boot
Spring Boot 文档https://docs.spring.io/spring-boot/index.html
Spring Initializr 项目生成器https://start.spring.io/
Spring GitHubhttps://github.com/spring-projects
Spring Cloud GitHubhttps://github.com/spring-cloud
Spring 版本支持信息https://spring.io/projects/spring-cloud#support

27.2 Spring Cloud 核心组件文档

组件链接
Spring Cloud Gatewayhttps://docs.spring.io/spring-cloud-gateway/reference/index.html
Spring Cloud Confighttps://docs.spring.io/spring-cloud-config/reference/index.html
Spring Cloud OpenFeignhttps://docs.spring.io/spring-cloud-openfeign/reference/index.html
Spring Cloud LoadBalancerhttps://docs.spring.io/spring-cloud-commons/reference/spring-cloud-commons/loadbalancer.html
Spring Cloud CircuitBreakerhttps://docs.spring.io/spring-cloud-circuitbreaker/reference/index.html
Spring Cloud Bushttps://docs.spring.io/spring-cloud-bus/docs/current/reference/html/
Spring Cloud Streamhttps://docs.spring.io/spring-cloud-stream/docs/current/reference/html/
Spring Cloud Kuberneteshttps://docs.spring.io/spring-cloud-kubernetes/reference/index.html
Spring Cloud Contracthttps://docs.spring.io/spring-cloud-contract/reference/index.html
Spring Cloud Vaulthttps://docs.spring.io/spring-cloud-vault/reference/index.html

27.3 Spring Cloud Alibaba 资源

名称链接
Spring Cloud Alibaba 项目页https://spring.io/projects/spring-cloud-alibaba
Spring Cloud Alibaba GitHubhttps://github.com/alibaba/spring-cloud-alibaba
Spring Cloud Alibaba 官方文档https://sca.aliyun.com/
Spring Cloud Alibaba 英文文档https://sca.aliyun.com/en/
Spring Cloud Alibaba Releaseshttps://github.com/alibaba/spring-cloud-alibaba/releases
Alibaba Cloud 微服务引擎 MSEhttps://www.aliyun.com/product/aliware/mse

27.4 Nacos 资源

名称链接
Nacos 官网https://nacos.io/
Nacos 英文官网https://nacos.io/en/
Nacos GitHubhttps://github.com/alibaba/nacos
Nacos 快速开始https://nacos.io/docs/latest/quickstart/quick-start/
Nacos Spring Cloud 快速开始https://nacos.io/en-us/docs/quick-start-spring-cloud.html
Nacos Releaseshttps://github.com/alibaba/nacos/releases

27.5 Sentinel / Seata / RocketMQ 资源

名称链接
Sentinel GitHubhttps://github.com/alibaba/Sentinel
Sentinel Wikihttps://github.com/alibaba/Sentinel/wiki
Sentinel Releaseshttps://github.com/alibaba/Sentinel/releases
Seata 官网https://seata.apache.org/
Seata GitHubhttps://github.com/apache/incubator-seata
Apache RocketMQ 官网https://rocketmq.apache.org/
Apache RocketMQ GitHubhttps://github.com/apache/rocketmq

27.6 相关基础资源

名称链接
Maven Centralhttps://central.sonatype.com/
Maven Repositoryhttps://mvnrepository.com/
MyBatis-Plus 官网https://baomidou.com/
MySQL 官网https://www.mysql.com/
Redis 官网https://redis.io/
RabbitMQ 官网https://www.rabbitmq.com/
Kafka 官网https://kafka.apache.org/
Docker 官网https://www.docker.com/
Kubernetes 官网https://kubernetes.io/
Prometheus 官网https://prometheus.io/
Grafana 官网https://grafana.com/
SkyWalking 官网https://skywalking.apache.org/

最后建议

如果你是为了学习和做项目,可以按下面路线选择:

小项目

Vue3 + Spring Boot + MySQL + Redis

中型项目

Vue3 + Spring Boot + Spring Cloud Alibaba + Nacos + Gateway + OpenFeign + MySQL + Redis

大型商城项目

Vue3 / App / 小程序
+ Spring Cloud Alibaba
+ Nacos
+ Gateway
+ OpenFeign
+ Sentinel
+ Seata
+ RocketMQ
+ MySQL
+ Redis
+ Elasticsearch
+ Docker / Kubernetes
+ Prometheus / Grafana / SkyWalking

学习顺序不要反过来:

Java 基础 -> Spring Boot -> MySQL/Redis -> Spring Security/JWT -> Spring Cloud -> Nacos/Gateway/OpenFeign -> Sentinel/MQ/Seata -> Docker 部署

更多推荐