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 功能强大且灵活,适合作为微服务架构的统一入口,结合服务发现、限流、鉴权等功能可有效简化分布式系统的入口层开发。

相关推荐
AOwhisky2 天前
Ceph系列第五期:Ceph 对象存储(RADOS Gateway)精讲
linux·运维·笔记·ceph·gateway·对象存储
西凉的悲伤3 天前
Spring Cloud Gateway介绍
java·spring cloud·gateway
苏渡苇4 天前
Spring Cloud Gateway 网关限流
spring cloud·gateway·springboot·网关限流
一个儒雅随和的男子5 天前
Spring cloud组件gateway网关详细剖析
spring·spring cloud·gateway
超梦dasgg5 天前
Gateway 鉴权场景:网关统一鉴权 + 业务应用决定放行规则
java·gateway
木雷坞5 天前
AI Gateway 接入大模型服务后首 token 慢排查:镜像、模型缓存和 GPU 节点
人工智能·缓存·gateway
明夜之约6 天前
Spring Cloud Gateway 深度解析:从路由原理到生产级网关实战
java·spring·spring cloud·gateway
tyler_download7 天前
深入深出openclaw:gateway 服务进程的启动逻辑
gateway
Upsy-Daisy7 天前
OpenClaw 源码解析(七):Gateway 控制平面与 WebSocket RPC 机制
websocket·平面·gateway
香菜烤面包7 天前
SGLang Model Gateway 核心功能解析
gateway