当前位置: 首页 > news >正文

Spring Cloud Gateway:微服务架构下的 API 网关详解

前言

在微服务架构中,API 网关(API Gateway) 是一个关键的组件,它充当了微服务架构的“门面”,负责路由、认证、限流、熔断、日志记录等通用功能。随着微服务数量的增加,传统的网关方案(如 Zuul、Nginx 等)逐渐暴露出性能、可扩展性、灵活性等方面的不足。

Spring Cloud Gateway 是 Spring Cloud 官方推出的第二代 API 网关解决方案,基于 Project ReactorNetty 构建,具有非阻塞、响应式、高性能的特点,是目前构建微服务架构中最主流的网关实现之一。


一、Spring Cloud Gateway 简介

Spring Cloud Gateway 是 Spring Cloud Alibaba 的一部分,但它本身是 Spring Cloud 的原生组件。它使用了 WebFlux + Reactor 技术栈,基于 Netty 提供异步非阻塞的网络通信能力。

1.1 核心概念

Spring Cloud Gateway 有三个核心概念:

  • Route(路由):路由是网关的基本单元,由 ID、目标 URI、断言集合和过滤器集合组成。
  • Predicate(断言):用于匹配请求是否符合某个条件(如路径、方法、头信息等)。
  • Filter(过滤器):用于修改请求和响应,如添加头、修改请求体、限流、鉴权等。

二、Spring Cloud Gateway 的优势

与 Zuul 相比,Spring Cloud Gateway 有以下优势:

特性Spring Cloud GatewayZuul
性能非阻塞,基于 WebFlux 和 Netty,性能更高阻塞式 I/O,性能较低
支持协议HTTP/HTTPS仅支持 HTTP
可扩展性更容易扩展自定义断言和过滤器扩展性较差
集成与 Spring Cloud 生态无缝集成(如 Nacos、Sentinel)集成较为复杂
社区活跃度活跃,持续更新停止更新,转向 Gateway

三、快速入门

3.1 添加依赖

<dependencies><!-- Spring Cloud Gateway --><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-gateway</artifactId></dependency><!-- Eureka Client(可选) --><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-netflix-eureka-client</artifactId></dependency>
</dependencies>

3.2 配置文件(application.yml)

server:port: 8080spring:application:name: gateway-servicecloud:gateway:routes:- id: user-serviceuri: lb://user-servicepredicates:- Path=/api/user/**filters:- StripPrefix=1

上面的配置表示:

  • 所有访问 /api/user/** 的请求都会被转发到 user-service 微服务。
  • lb://user-service 表示使用负载均衡访问服务。
  • StripPrefix=1 表示去掉第一层路径 /api/user,只保留后面的部分。

四、核心组件详解

4.1 Route(路由)

路由是网关的核心配置单元,由以下几个部分组成:

  • id:路由的唯一标识
  • uri:目标服务的地址,支持 http://, lb://(负载均衡)等
  • predicates:一组断言,用于匹配请求
  • filters:一组过滤器,用于修改请求或响应

示例:

routes:- id: order-serviceuri: http://localhost:8082predicates:- Method=POST- Path=/api/order/**filters:- AddRequestHeader=X-Request-Id, 123456

4.2 Predicate(断言)

断言用于判断请求是否符合某个条件。Spring Cloud Gateway 提供了多种内置的断言,常见的包括:

断言说明
Path=/api/user/**匹配指定路径
Method=GET匹配指定 HTTP 方法
Header=X-Request-ID, \d+匹配 Header 值是否符合正则
Query=username, abc.*匹配查询参数是否符合正则
After=2025-01-01T00:00:00+08:00[Asia/Shanghai]匹配请求是否在指定时间之后
Between=2025-01-01T00:00:00+08:00[Asia/Shanghai], 2025-12-31T23:59:59+08:00[Asia/Shanghai]匹配请求是否在某个时间段内

4.3 Filter(过滤器)

过滤器用于在请求前后对请求或响应进行处理。Spring Cloud Gateway 分为两种类型的过滤器:

  • GatewayFilter(局部过滤器):作用于特定路由
  • GlobalFilter(全局过滤器):作用于所有路由
常见过滤器示例
过滤器说明
StripPrefix=1去除路径前缀
AddRequestHeader=X-Request-ID, 123456添加请求头
RewritePath=/api/(?<segment>.*), /$\{segment}重写路径
Hystrix=commandName=fallback, fallbackUri=forward:/fallback熔断处理
RateLimiter=redis-rate-limiter.replenishRate=10, redis-rate-limiter.burstCapacity=20限流

五、自定义断言和过滤器

5.1 自定义断言工厂

@Component
public class MyHeaderRoutePredicateFactory extends AbstractRoutePredicateFactory<MyHeaderRoutePredicateFactory.Config> {public MyHeaderRoutePredicateFactory() {super(Config.class);}@Overridepublic Predicate<ServerWebExchange> apply(Config config) {return exchange -> {String header = exchange.getRequest().getHeaders().getFirst("X-Custom-Header");return config.value.equals(header);};}public static class Config {private String value;public String getValue() {return value;}public void setValue(String value) {this.value = value;}}
}

使用方式:

predicates:- MyHeader=X-Custom-Value

5.2 自定义过滤器工厂

@Component
public class MyRequestTimeGatewayFilterFactory extends AbstractGatewayFilterFactory<MyRequestTimeGatewayFilterFactory.Config> {public MyRequestTimeGatewayFilterFactory() {super(Config.class);}@Overridepublic GatewayFilter apply(Config config) {return (exchange, chain) -> {long start = System.currentTimeMillis();return chain.filter(exchange).then(Mono.fromRunnable(() -> {long end = System.currentTimeMillis();System.out.println("请求耗时:" + (end - start) + " ms");}));};}public static class Config {// 可以添加配置项}
}

使用方式:

filters:- MyRequestTime

六、集成服务注册与发现(如 Nacos、Eureka)

Spring Cloud Gateway 可以自动从服务注册中心获取服务实例,并进行负载均衡调用。

示例(Eureka)

spring:cloud:gateway:routes:- id: user-serviceuri: lb://user-servicepredicates:- Path=/user/**

其中 lb://user-service 表示使用负载均衡访问服务。


七、集成熔断机制(Hystrix)

Spring Cloud Gateway 支持集成 Hystrix 进行熔断处理。

spring:cloud:gateway:routes:- id: user-serviceuri: lb://user-servicepredicates:- Path=/user/**filters:- name: Hystrixargs:name: fallbackfallbackUri: forward:/fallback

创建一个 fallback 接口:

@RestController
public class FallbackController {@GetMapping("/fallback")public String fallback() {return "服务不可用,请稍后再试!";}
}

八、限流(RateLimiter)

Spring Cloud Gateway 支持基于 Redis 的限流策略。

spring:cloud:gateway:routes:- id: user-serviceuri: lb://user-servicepredicates:- Path=/user/**filters:- name: RequestRateLimiterargs:rate-limiter: redis-rate-limiterkey-resolver: #{@userKeyResolver}

自定义 Key 解析器:

@Bean
public KeyResolver userKeyResolver() {return exchange -> Mono.just(exchange.getRequest().getRemoteAddress().getHostName());
}

九、日志与监控

Spring Cloud Gateway 支持与 Sleuth、Zipkin 集成,进行链路追踪;也可以使用 Prometheus + Grafana 进行性能监控。


十、总结

Spring Cloud Gateway 是当前构建微服务架构中最推荐的 API 网关实现,它基于响应式编程模型,具备高性能、低延迟、可扩展性强等优点。通过 Route、Predicate、Filter 三大核心组件,可以灵活实现路由、鉴权、限流、熔断等常见功能。


十一、参考资料

  • Spring Cloud Gateway 官方文档
  • Spring Cloud Alibaba 官方文档
  • Spring WebFlux 官方文档
http://www.dtcms.com/a/299199.html

相关文章:

  • GRE及MGRE应用综合实验
  • ICMPv4报文类型详解表
  • OpenCV学习探秘之二 :数字图像的矩阵原理,OpenCV图像类与常用函数接口说明,及其常见操作核心技术详解
  • 生猪产业新生态:结构调整与种养结合,筑牢农业强国根基
  • Linux内核设计与实现 - 课程大纲
  • Android WorkManager 详解:高效管理后台任务
  • Ruby 数据库访问 - DBI 教程
  • 基于深度学习的胸部 X 光图像肺炎分类系统(七)
  • 基于POD和DMD的压气机叶片瞬态流场分析与神经网络预测
  • java8 List常用基本操作(去重,排序,转换等)
  • 联表实现回显功能
  • 经典IDE之Turbo C
  • HAProxy 实验指南:从零开始搭建高可用负载均衡系统
  • haproxy原理及实战部署
  • AI Agent开发学习系列 - LangGraph(2): 用LangGraph创建我们的第一个Agent(练习解答)
  • Java后端通过hutool接口发请求
  • 【LeetCode刷题指南】--队列实现栈,栈实现队列
  • DocC的简单使用
  • VisionPro系列讲解 - 03 Simulator 模拟器使用
  • 【MySQL数据库备份与恢复2】备份的三种常用方法
  • 在C#中判断两个列表数据是否相同
  • 前缀和-238-除自身以外数组的乘积-力扣(LeetCode)
  • 数学建模国赛历年赛题与优秀论文学习思路
  • 弹性元空间:JEP 387 深度解析与架构演进
  • Windows Server存储池,虚拟磁盘在系统启动后不自动连接需要手动连接
  • Matrix Theory study notes[5]
  • Mybatis学习之配置文件(三)
  • 数学专业数字经济转型全景指南
  • 广东省省考备考(第五十七天7.26)——数量、言语(强化训练)
  • Linux c++ CMake常用操作