gateway

Spring Cloud Gateway 是 Spring Cloud 生态系统中的 API 网关组件,基于 Spring 5、Spring Boot 2.x 和 Project Reactor(响应式编程)构建,主要用于微服务架构中作为统一入口,实现请求路由、过滤、限流、鉴权等功能。以下是核心知识点和使用指南:

一、核心概念

  1. Route(路由)

    网关的基本构建块,由一个 ID、目标 URI(转发地址)、一组 Predicate(断言)和一组 Filter(过滤器)组成。当 Predicate 匹配时,请求会被路由到目标 URI。

  2. Predicate(断言)

    基于 Java 8 的 Predicate,用于匹配 HTTP 请求(如路径、方法、请求头、参数等)。例如:Path=/api/** 匹配路径以 /api/ 开头的请求。

  3. Filter(过滤器)

    分为 Pre 过滤器(请求转发前执行,如鉴权、参数修改)和 Post 过滤器(响应返回前执行,如响应头修改、日志记录)。支持自定义过滤逻辑。

二、快速入门(基于 Spring Boot)

  1. 添加依赖

在 pom.xml 中引入 Spring Cloud Gateway 和服务发现(如 Nacos/Eureka,可选):

org.springframework.cloud

spring-cloud-starter-gateway
com.alibaba.cloud spring-cloud-starter-alibaba-nacos-discovery

  1. 基础配置(application.yml)

通过配置文件定义路由规则:

spring:

cloud:

gateway:

routes:

  • id: user-service # 路由ID(唯一)

uri: http://localhost:8081 # 目标服务地址(或直接写服务名,如 lb://user-service,需配合服务发现)

predicates:

  • Path=/api/user/** # 匹配路径

filters:

  • StripPrefix=1 # 转发时去掉路径中的第一个前缀(如 /api/user/get → /user/get)
  1. 启动类

无需额外注解(Spring Cloud Gateway 自动配置):

@SpringBootApplication

public class GatewayApplication {

public static void main(String[] args) {

SpringApplication.run(GatewayApplication.class, args);

}

}

三、常用功能

  1. 动态路由(结合服务发现)

若使用 Nacos/Eureka 等服务发现组件,可通过服务名路由(需开启服务发现):

spring:

cloud:

gateway:

discovery:

locator:

enabled: true # 开启基于服务发现的路由(默认路径:/服务名/**)
routes:

  • id: user-service
    uri: lb://user-service # lb:// 表示负载均衡(需引入负载均衡依赖,如 spring-cloud-starter-loadbalancer)
    predicates:
  • Path=/api/user/**
  1. 自定义全局过滤器(GlobalFilter)

实现 GlobalFilter 和 Ordered 接口,对所有路由生效(如鉴权):

@Component

public class AuthGlobalFilter implements GlobalFilter, Ordered {

@Override

public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) {

// 示例:检查请求头中的 token

String token = exchange.getRequest().getHeaders().getFirst("token");

if (token == null || token.isEmpty()) {

exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);

return exchange.getResponse().setComplete(); // 终止请求

}

return chain.filter(exchange); // 放行

}

复制代码
@Override
public int getOrder() {
    return 0; // 过滤器顺序(值越小,优先级越高)
}

}

  1. 限流(基于 Redis)

使用 Redis 实现令牌桶限流,需添加 Redis 依赖:

org.springframework.boot

spring-boot-starter-data-redis-reactive

配置限流过滤器:

spring:

cloud:

gateway:

routes:

  • id: user-service

uri: lb://user-service

predicates:

  • Path=/api/user/**

filters:

  • name: RequestRateLimiter # 限流过滤器

args:

redis-rate-limiter.replenishRate: 10 # 每秒生成10个令牌

redis-rate-limiter.burstCapacity: 20 # 令牌桶最大容量

key-resolver: "#{@userKeyResolver}" # 限流键解析器(按用户IP限流)

自定义限流键解析器:

@Configuration

public class RateLimitConfig {

@Bean

public KeyResolver userKeyResolver() {

// 按请求IP限流

return exchange -> Mono.just(exchange.getRequest().getRemoteAddress().getAddress().getHostAddress());

}

}

  1. 跨域配置(CORS)

全局跨域配置:

@Configuration

public class CorsConfig {

@Bean

public CorsWebFilter corsWebFilter() {

CorsConfiguration config = new CorsConfiguration();

config.addAllowedMethod(""); // 允许所有请求方法
config.addAllowedOrigin("
"); // 允许所有源(生产环境需指定具体域名)

config.addAllowedHeader("*"); // 允许所有请求头

复制代码
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", config); // 对所有路径生效
    return new CorsWebFilter(source);
}

}

四、注意事项

  1. 响应式编程:Spring Cloud Gateway 基于 Reactor,避免使用阻塞式代码(如 Thread.sleep()),否则会导致性能问题。
  2. 版本兼容:需匹配 Spring Boot 和 Spring Cloud 版本(参考 https://spring.io/projects/spring-cloud)。
  3. 性能优化:生产环境建议开启响应式 Redis、调整线程池(如 Netty 的 EventLoop 线程数)。

五、常见问题

• 路由不生效:检查 Predicate 是否匹配请求、目标 URI 是否正确、服务发现是否正常。

  • 过滤器执行顺序:通过 Ordered 接口或 @Order 注解调整优先级(值越小越先执行)。
  • 跨域失效:确保 CORS 过滤器优先级高于路由过滤器(可通过 getOrder() 调整)。

Spring Cloud Gateway 功能强大且灵活,适合作为微服务架构的统一入口,结合服务发现、限流、鉴权等功能可有效简化分布式系统的入口层开发。

相关推荐
一个public的class1 天前
前后端 + Nginx + Gateway + K8s 全链路架构图解
前端·后端·nginx·kubernetes·gateway
uNke DEPH2 天前
SpringCloud Gateway 集成 Sentinel 详解 及实现动态监听Nacos规则配置实时更新流控规则
spring cloud·gateway·sentinel
ERBU DISH3 天前
当遇到 502 错误(Bad Gateway)怎么办
gateway
小超同学你好6 天前
OpenClaw 深度解析与源代码导读 · 第3篇:Gateway——常驻控制面、单端口多协议与进程骨架
人工智能·深度学习·语言模型·gateway
w6100104667 天前
Cka-2026-gateway解释
gateway·k8s·cka
岳来8 天前
网络小白docker network create时如何指定subnet 和gateway
网络·docker·gateway·subnet
如来神掌十八式9 天前
nginx + spring gateway+spring 服务_nginx 转发到 gateway
nginx·spring·gateway
晏宁科技YaningAI9 天前
分布式通信系统的容错机制
网络协议·微服务·系统架构·gateway·信息与通信·paas
爱淋雨的男人11 天前
网关gateway详解
gateway