文章目录
- 1、Spring Cloud Gateway 详细介绍
- 1.1. 统一入口(Single Entry Point)
- 1.2. 请求路由(Request Routing)
- 1.3. 负载均衡(Load Balancing)
- 1.4. 流量控制(Rate Limiting)
- 1.5. 身份认证(Authentication & Authorization)
- 1.6. 协议转换(Protocol Translation)
- 1.7. 系统监控(Monitoring & Logging)
- 1.8. 安全防护(Security Protection)
- 2、Spring Cloud Gateway的使用
- 2.2. 两种gateway模式
- 2.2. 使用案例需求
- 2.3. 创建gateway模块
- 2.4. 启动gateway模块
- 3、配置路由规则
- 4、启动多个服务进行测试
1、Spring Cloud Gateway 详细介绍
Spring Cloud Gateway 作为微服务架构的 API 网关,提供统一入口、请求路由、负载均衡、流量控制、身份认证、协议转换、系统监控、安全防护等功能,能够高效管理 API 请求流量,并提升系统的安全性和稳定性。
1.1. 统一入口(Single Entry Point)
微服务架构中,每个微服务都有自己的 API,直接暴露所有服务会导致维护困难、安全风险增加。
Spring Cloud Gateway 解决方案:
通过单一网关,所有外部请求都必须先通过 API 网关,再路由到具体微服务。
隐藏微服务细节,外部只需访问网关地址,不直接访问后端服务。
✅ 示例:配置 API 入口
spring:cloud:gateway:routes:- id: user-serviceuri: lb://user-servicepredicates:- Path=/user/**- id: order-serviceuri: lb://order-servicepredicates:- Path=/order/**
-
/user/** 的请求被路由到 user-service
-
/order/** 的请求被路由到 order-service
-
客户端只需要请求 API 网关,而无需知道后端微服务的实际地址。
1.2. 请求路由(Request Routing)
需要根据路径、请求头、参数等,动态转发到不同的微服务。
Spring Cloud Gateway 解决方案:
- 基于 Path、Header、Query 参数等规则,智能路由。
✅ 示例:多种路由规则
routes:- id: auth-serviceuri: lb://auth-servicepredicates:- Path=/auth/** # 按路径匹配- Method=POST # 按请求方法匹配- Header=X-Device, Mobile # 按请求头匹配
-
路径规则:所有 /auth/** 请求都会转发到 auth-service。
-
请求方法:仅支持 POST 请求。
-
请求头规则:X-Device=Mobile 时才会匹配。
1.3. 负载均衡(Load Balancing)
单个微服务实例可能会过载,需要将流量分发到多个实例,提高可用性。
Spring Cloud Gateway 解决方案:
- 内置 Spring Cloud LoadBalancer,支持基于服务注册中心(Eureka、Consul、Nacos)自动均衡流量。
✅ 示例:开启负载均衡
uri: lb://order-service
- lb:// 表示启用负载均衡,请求会被分发到 order-service 的多个实例。
1.4. 流量控制(Rate Limiting)
突发流量可能导致服务崩溃,需要限制单个 IP 或用户的请求速率。
Spring Cloud Gateway 解决方案:
- 基于 Redis 令牌桶算法,支持用户级、IP 级限流。
✅ 示例:限流配置
filters:- name: RequestRateLimiterargs:redis-rate-limiter.replenishRate: 5 # 每秒 5 个请求redis-rate-limiter.burstCapacity: 10 # 最大 10 个请求
- 每秒最多 5 个请求,超过速率的请求会被拒绝。
1.5. 身份认证(Authentication & Authorization)
需要确保只有合法用户可以访问微服务,防止未授权访问。
Spring Cloud Gateway 解决方案:
集成 Spring Security + OAuth2/JWT 进行身份认证。
TokenRelay 机制,将身份验证信息传递给下游服务。
✅ 示例:JWT 认证
filters:- name: TokenRelay # 自动转发 JWT Token
- TokenRelay 过滤器 会自动从请求中提取 JWT 令牌,并传递给后端微服务进行身份验证。
1.6. 协议转换(Protocol Translation)
有些微服务可能只支持 HTTP 或 HTTPS,但客户端请求可能是 WebSocket、gRPC 等。
Spring Cloud Gateway 解决方案:
支持 WebSocket 转发
支持 HTTP 转 HTTPS
✅ 示例:WebSocket 转发
routes:- id: ws-routeuri: ws://localhost:9000predicates:- Path=/ws/**
- /ws/** 开头的 WebSocket 请求会被转发到 localhost:9000。
1.7. 系统监控(Monitoring & Logging)
需要监控网关的流量情况、请求延迟、异常情况。
Spring Cloud Gateway 解决方案:
结合 Spring Boot Actuator,提供健康检查、流量监控
支持 Prometheus + Grafana 进行可视化监控
支持 Zipkin/Jaeger 进行链路追踪
✅ 示例:开启 Actuator 监控
management:endpoints:web:exposure:include: gateway
- 访问 /actuator/gateway/routes 可查看所有路由情况。
✅ 结合 Prometheus 进行监控
management:metrics:export:prometheus:enabled: true
- 可在 Grafana 中展示流量数据。
1.8. 安全防护(Security Protection)
API 网关必须具备基础安全防护能力,防止恶意攻击。
Spring Cloud Gateway 解决方案:
- 黑白名单过滤(基于 IP、用户角色)
- 防止 SQL 注入、XSS
- 请求加密(TLS/SSL)
- 防止 DDoS 攻击(限流 + 认证)
示例:IP 访问控制
filters:- name: IpFilterargs:deny-lists: 192.168.1.100 # 禁止此 IP 访问
- 可以防止恶意 IP 访问 API 网关。
- 结论
功能 | Spring Cloud Gateway 解决方案 |
---|---|
统一入口 | 通过网关管理所有微服务入口 |
请求路由 | 按路径、请求头、参数等匹配路由 |
负载均衡 | 内置 LoadBalancer,自动分流流量 |
流量控制 | 令牌桶算法限流,防止过载 |
身份认证 | 支持 JWT/OAuth2 认证 |
协议转换 | WebSocket 代理,HTTPS 转换 |
系统监控 | Actuator、Prometheus、Grafana |
安全防护 | 黑白名单、DDoS 防护 |
2、Spring Cloud Gateway的使用
2.2. 两种gateway模式
Spring Cloud Gateway 提供了两种模式来运行 API 网关:
-
Spring Cloud Gateway Reactive Server(基于 Spring WebFlux)
-
Spring Cloud Gateway Server MVC(基于 Spring MVC)
推荐使用第一种模式。
2.2. 使用案例需求
需求
- 1.客户端发送 /api/order/**转到service-order
- 2.客户端发送 /api/product/**转到 service-product
- 3.以上转发有负载均衡效果
2.3. 创建gateway模块
引入依赖(这里同时需要引入nacos依赖)
<dependencies><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId></dependency><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-gateway</artifactId></dependency></dependencies>
创建gateway主启动类:
package com.tigerhhzz.gateway;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;/*** @Author tigerhhzz* @Date 2025 03 28 02 00**/
@EnableDiscoveryClient
@SpringBootApplication
public class GatewayMainApplication {public static void main(String[] args) {System.out.println("--------GatewayMainApplication---------start successful!");SpringApplication.run(GatewayMainApplication.class,args);}
}
编写配置文件:
application.yml
spring:application:name: gatewaycloud:nacos:server-addr: 127.0.0.1:8848server:port: 80
2.4. 启动gateway模块
启动gateway主启动类,查看nacoa服务中心
3、配置路由规则
application.yml
spring:profiles:active:- routesapplication:name: gatewaycloud:nacos:server-addr: 127.0.0.1:8848server:port: 80
application-routes.yml
spring:cloud:gateway:routes:- id: order-routeuri: lb://service-orderpredicates:- Path=/api/order/**- id: product-routeuri: lb://service-productpredicates:- Path=/api/product/**
在每个控制器controller上加上配置文件中断言一致的路径
@RequestMapping("/api/order")@RequestMapping("/api/product")
4、启动多个服务进行测试
发送请求到order-service的两个服务,进行了负载均衡!!!
别害怕付出没有回报,那些看似平淡无奇的日子,都是成长的伏笔。