🌈 微服务智能门卫:Spring Cloud Gateway 超详细实战笔记(CSDN 可用)
✨ 开篇鸡汤
微服务时代,API 网关就像是你家小区的智能门卫🚪,帮你把各种快递、外卖、访客统统拦在门外,只留下合法的、经过安检的"流量"进入你家(微服务)。今天,我们就来手把手搭建一个 Spring Cloud Gateway 网关,让你的微服务入口安全又高效!
🎯 一、为什么微服务需要 API 网关?
在微服务架构中,一个系统会被拆分成多个小服务(订单服务、库存服务、账户服务......)。如果让客户端直接调用每个微服务,会出现以下问题:
问题描述 | 举个栗子🌰 |
---|---|
📍服务地址太多,客户端难以维护 | 前端同学要记一堆 IP 和端口,头秃! |
🔐每个服务都要做鉴权限流,重复造轮子 | 每个服务都要写一遍登录验证,累! |
🌐跨域、协议转换、流量控制等问题 | 前端想 HTTPS,后端只支持 HTTP,尴尬! |
因此,我们引入 API 网关(Gateway),作为所有流量的统一入口,解决以上痛点。
🚀 二、Spring Cloud Gateway 是什么?
🏷️ 官方定义 :Spring Cloud Gateway 是 Spring Cloud 官方推出的第二代网关框架,用来取代 Netflix Zuul。
🎨 核心特点
特性 | 说明 |
---|---|
⚡ 响应式网关 | 基于 WebFlux + Netty + Reactor 实现,性能炸裂! |
🧩 Filter 链 | 通过过滤器实现鉴权、限流、监控等功能 |
🚫 不依赖 Servlet | 不能跑在 Tomcat/Jetty 等传统容器中,也不能打成 war 包 |
⚠️ 注意:Spring Cloud Gateway 不能和
spring-webmvc
一起用,会冲突!
🛠️ 三、实战:快速接入 Spring Cloud Gateway
1️⃣ 创建网关模块 mall-gateway
在你的项目中新建一个模块,命名为 mall-gateway
。
2️⃣ 引入依赖(pom.xml)
xml
<!-- Spring Cloud Gateway -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<!-- 注意:排除 spring-webmvc 冲突 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webmvc</artifactId>
</exclusion>
</exclusions>
</dependency>
3️⃣ 配置 application.yml(以订单服务为例)
yaml
server:
port: 18888 # 🚪 网关端口
spring:
application:
name: mall-gateway
cloud:
gateway:
routes:
- id: order-service
uri: lb://mall-order # 🎯 订单服务注册在注册中心的名字
predicates:
- Path=/order/** # 🛤️ 路径匹配
filters:
- StripPrefix=1 # 🗂️ 去掉前缀
- id: inventory-service
uri: lb://mall-inventory
predicates:
- Path=/inventory/**
filters:
- StripPrefix=1
- id: account-service
uri: lb://mall-account
predicates:
- Path=/account/**
filters:
- StripPrefix=1
💡 小提示 :
这些配置可以放到 配置中心(如 Nacos、Consul) ,新建一个
mall-gateway.yml
文件统一管理。
🧪 四、启动 & 测试
✅ 启动网关服务
启动 mall-gateway
模块,确保注册中心(如 Nacos)已启动。
🧪 Postman 测试
-
访问网关下单接口:
POST http://localhost:18888/order/create
-
网关会自动将请求转发到
mall-order
服务。
🖥️ 前端联调
-
修改前端
order.html
中的请求地址:从原来的
http://mall-order:8080/order/create
改为
http://mall-gateway:18888/order/create
-
测试下单是否成功!
🧩 五、小结 & 后续展望
核心要点 | 一句话总结 |
---|---|
🚪 网关定位 | 微服务架构的统一流量入口 |
⚡ 技术选型 | Spring Cloud Gateway,基于响应式编程 |
🧪 实战步骤 | 创建模块 → 引入依赖 → 配置路由 → 启动测试 |
🎓 后续进阶 :
在 Spring Cloud Gateway 实战课程 中,我们将深入讲解:
- 🛡️ 自定义全局过滤器(鉴权、日志、灰度发布)
- 💥 限流熔断(基于 Redis 令牌桶、Sentinel)
- 🌐 跨域处理、协议转换、负载均衡策略
🌟 彩蛋:一句话总结
Gateway 就像是你微服务世界的"智能门卫",帮你挡住非法流量,放行合法请求,让你的微服务高枕无忧!