Spring Boot 网关详细使用教程:Spring Cloud Gateway 从入门到精通

Spring Boot 网关详细使用教程:Spring Cloud Gateway 从入门到精通

Spring Boot 网关详细使用教程

一、Spring Boot 网关简介

什么是网关

API 网关是微服务架构中的核心组件,作为系统的统一入口,负责请求的路由、认证、限流、监控等功能。

网关的作用

功能 说明
请求路由 将请求转发到对应的微服务
身份认证 统一处理用户认证和授权
限流熔断 保护后端服务免受流量冲击
日志监控 收集请求日志和性能指标
跨域处理 解决浏览器的 CORS 问题
协议转换 HTTP 到 gRPC、WebSocket 等

常见网关对比

| 网关 | 特点 | 适用场景 |
|——|——|———-|
| Spring Cloud Gateway | 基于 Spring WebFlux,非阻塞 | 微服务架构 |
| Zuul | 基于 Servlet,阻塞 I/O | 遗留系统 |
| Nginx | 高性能,配置复杂 | 静态资源、反向代理 |
| Kong | 基于 OpenResty,插件丰富 | 云原生环境 |

二、Spring Cloud Gateway 核心概念

三大核心组件

请求流程:
客户端 → Route(路由) → Predicate(断言) → Filter(过滤器) → 后端服务

Route(路由)

路由是网关的基本组成单元,包含 ID、目标 URI、断言和过滤器。

“`yaml
spring:
cloud:
gateway:
routes:

  • id: user-service

uri: lb://user-service
predicates:

  • Path=/api/users/**

filters:

  • AddRequestHeader=X-Request-Source, Gateway

Predicate(断言)

断言用于匹配请求,只有匹配成功的请求才会被路由。

yaml
predicates:

  • Path=/api/users/** # 路径断言
  • Method=GET,POST # 方法断言
  • Header=X-Token,.* # 请求头断言
  • Query=user-id,.* # 查询参数断言

Filter(过滤器)

过滤器在请求转发前后执行逻辑。

yaml
filters:

  • name: RequestRateLimiter # 内置过滤器

args:
redis-rate-limiter.reqs: 100
redis-rate-limiter.period: 1

  • name: CustomAuthFilter # 自定义过滤器

三、快速开始 - 创建第一个网关

项目依赖

xml



org.springframework.cloud
spring-cloud-starter-gateway



org.springframework.cloud
spring-cloud-starter-loadbalancer



org.springframework.boot
spring-boot-starter-actuator


启动类

java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class GatewayApplication {
public static void main(String[] args) {
SpringApplication.run(GatewayApplication.class, args);
}
}


配置文件

yaml

application.yml

spring:
application:
name: gateway
cloud:
gateway:
discovery:
locator:
enabled: true # 启用服务发现路由
routes:

  • id: user-service

uri: lb://user-service
predicates:

  • Path=/api/users/**

filters:

  • StripPrefix=1

server:
port: 8080


四、路由配置

静态路由配置

yaml
spring:
cloud:
gateway:
routes:
# 基础路由

  • id: user-service

uri: http://localhost:8081
predicates:

  • Path=/api/users/**

filters:

  • RemoveRequestHeader=Cookie

# 多个断言

  • id: order-service

uri: http://localhost:8082
predicates:

  • Path=/api/orders/**
  • Method=GET,POST

filters:

  • AddResponseHeader=X-Response-Time, {timestamp}

# 路由分组

  • id: product-service

uri: http://localhost:8083
predicates:

  • Path=/api/products/**

filters:

  • name: Retry

args:
retries: 3
statuses: BAD_GATEWAY


动态路由配置

java
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class DynamicRouteConfig {

@Bean
public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
return builder.routes()
.route(“dynamic-route”, r -> r
.path(“/api/dynamic/**”)
.filters(f -> f
.stripPrefix(1)
.addRequestHeader(“X-Dynamic”, “true”)
)
.uri(“lb://dynamic-service”))
.route(“temp-route”, r -> r
.path(“/api/temp/**”)
.uri(“http://temp-service:8080”)
)
.build();
}
}


从配置中心动态加载

yaml

application.yml

spring:
cloud:
gateway:
routes:

  • id: dynamic-route

uri: lb://dynamic-service
predicates:

  • Path=/api/dynamic/**

filters:

  • name: CircuitBreaker

args:
name: defaultCb
fallbackUri: forward:/fallback

刷新路由

@RestController
public class RefreshController {
@Autowired
private RefreshScope refreshScope;

@PostMapping(“/refresh/route”)
public void refreshRoute() {
// 通过 /actuator/refresh 刷新
}
}


五、断言的使用

Path 断言(路径匹配)

yaml
predicates:

  • Path=/api/users/** # 匹配所有用户路径
  • Path=/api/orders/{id} # 带参数路径
  • Path=/api/products/{id}/detail # 多级参数

Method 断言(请求方法)

yaml
predicates:

  • Method=GET # GET 请求
  • Method=GET,POST # 多个方法
  • Method=!DELETE # 排除 DELETE

Header 断言(请求头匹配)

yaml
predicates:

  • Header=X-Auth-Token,.* # 只要有此头部
  • Header=X-User-Id,digital-.* # 正则匹配
  • Header=Accept,application/json # 精确匹配

Query 断言(查询参数)

yaml
predicates:

  • Query=user-id,.* # 查询参数存在
  • Query=page,[1-9] # 数值范围
  • Query=sort,asc|desc # 多个值匹配

组合断言

yaml
predicates:

  • Predicate1: Path=/api/admin/**
  • Predicate2: Method=POST
  • Predicate3: Header=X-Admin-Token,.*

以上三个条件同时满足


六、过滤器

内置过滤器

yaml
filters:
# 请求头处理

  • AddRequestHeader=X-Request-Id, {UUID}
  • RemoveRequestHeader=Cookie
  • SetRequestHeader=X-Forwarded-For, {remoteAddr}

# 路径处理

  • StripPrefix=1 # 去除一级路径
  • StripPrefix=2 # 去除两级路径

# 响应处理

  • AddResponseHeader=X-Response-Id, {UUID}

# 安全

  • Secure # 强制 HTTPS
  • SecureHeaders # 添加安全头

# 限流

  • RequestRateLimiter=100,1

# 重试

  • Retry=3,BAD_GATEWAY

# 熔断

  • CircuitBreaker=serviceCb,fallbackUri=/fallback

自定义过滤器

java
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class CustomAuthFilter implements GlobalFilter, Ordered {

@Override
public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) {
String token = exchange.getRequest().getHeaders()
.getFirst(“X-Auth-Token”);

if (token == null || token.isEmpty()) {
exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
return exchange.getResponse().setComplete();
}

// 验证 Token 逻辑
if (!validateToken(token)) {
exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
return exchange.getResponse().setComplete();
}

return chain.filter(exchange);
}

private boolean validateToken(String token) {
// 实际验证逻辑
return token.startsWith(“Bearer “);
}

@Override
public int getOrder() {
return -1; // 优先级,值越小优先级越高
}
}


全局过滤器

java
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class LoggingFilter implements GlobalFilter {

@Override
public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) {
ServerHttpRequest request = exchange.getRequest();
System.out.println(“Request: ” + request.getMethod() + ” ” + request.getURI());

long start = System.currentTimeMillis();

return chain.filter(exchange)
.then(Mono.fromRunnable(() -> {
long duration = System.currentTimeMillis() – start;
System.out.println(“Response: ” + duration + “ms”);
}));
}
}


七、跨域配置

配置方式一:代码配置

java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;

@Configuration
public class CorsConfig {

@Bean
public CorsWebFilter corsFilter() {
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOriginPattern(“*”);
config.addAllowedHeader(“*”);
config.addAllowedMethod(“*”);
config.setMaxAge(3600L);

UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration(“/**”, config);

return new CorsWebFilter(source);
}
}


配置方式二:YAML 配置

yaml
spring:
cloud:
gateway:
globalcors:
cors-configs:
add-to-simple-url-handler: true
/**:
allowed-origins: “*”
allowed-methods: “*”
allowed-headers: “*”
allow-credentials: true
max-age: 3600


八、监控和日志

Actuator 端点

yaml
management:
endpoints:
web:
exposure:
include: health,info,metrics,gateway
endpoint:
gateway:
enabled: true
metrics:
tags:
application: ${spring.application.name}


监控指标

bash

获取网关路由信息

curl http://localhost:8080/actuator/gateway/routes

获取网关指标

curl http://localhost:8080/actuator/prometheus | grep gateway

路由刷新

curl -X POST http://localhost:8080/actuator/gateway/refresh


日志配置

yaml

application.yml

logging:
level:
org.springframework.cloud.gateway: DEBUG
reactor.netty: DEBUG

logback-spring.xml



logs/gateway.log
%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} – %msg%n





链路追踪

xml

org.springframework.cloud
spring-cloud-starter-sleuth


yaml
spring:
sleuth:
sampler:
probability: 1.0
zipkin:
base-url: http://localhost:9411


九、最佳实践

性能优化

yaml
spring:
cloud:
gateway:
httpclient:
connect-timeout: 1000
response-timeout: 3s
pool:
type: ELASTIC
max-connections: 500
Acquire-timeout: 45000


安全配置

yaml
spring:
cloud:
gateway:
routes:

  • id: public-route

uri: lb:public-service
predicates:

  • Path=/api/public/**

filters:

  • AddRequestHeader=X-Rate-Limit-Enabled, false
  • id: auth-route

uri: lb:auth-service
predicates:

  • Path=/api/auth/**

requires-ssl: true # 强制 HTTPS


熔断降级

yaml
spring:
cloud:
gateway:
routes:

  • id: payment-service

uri: lb:payment-service
predicates:

  • Path=/api/payment/**

filters:

  • name: CircuitBreaker

args:
name: paymentCb
fallbackUri: forward:/fallback/payment
status-codes: BAD_GATEWAY,SERVICE_UNAVAILABLE

  • id: fallback-route

uri: http://localhost:8080
predicates:

  • Path=/fallback/**

限流配置

java
import org.springframework.cloud.gateway.filter.factory.RequestRateLimiterGatewayFilterFactory;
import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.cloud.gateway.filter.ratelimit.RedisRateLimiter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RateLimiterConfig {

@Bean
public KeyResolver ipKeyResolver() {
return exchange ->
Mono.just(exchange.getRequest().getRemoteAddress().getAddress().getHostAddress());
}

@Bean
public KeyResolver userKeyResolver() {
return exchange ->
exchange.getRequest().getHeaders()
.getFirst(“X-User-Id”)
.flatMap(userId -> Mono.just(userId));
}
}
“`

总结

本文涵盖了 Spring Boot 网关的:

  • 网关简介 – 什么是网关、核心作用
  • 核心概念 – Route、Predicate、Filter
  • 快速开始 – 第一个网关项目
  • 路由配置 – 静态路由、动态路由
  • 断言使用 – Path、Method、Header、Query
  • 过滤器 – 内置过滤器、自定义过滤器
  • 跨域配置 – 代码和 YAML 两种方式
  • 监控日志 – Actuator、链路追踪
  • 最佳实践 – 性能、安全、熔断、限流

#SpringBoot #网关 #SpringCloud #微服务 #Gateway

文章已完成!

文件路径: `/home/node/.openclaw/agents/creator/workspace/content/Spring Boot 网关详细使用教程_20260425_2017.md`

请告诉我下一步操作(配图、发布等)!

© 版权声明
THE END
喜欢就支持一下吧
点赞8 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容