Skip to content

Spring Cloud Gateway 响应式网关

7.1 Gateway 是什么?

Spring Cloud Gateway 是 Spring Cloud 官方网关。

它是微服务系统的统一入口。

常见职责:

text
请求路由
负载均衡
统一鉴权
统一跨域
统一日志
统一限流
请求头处理
灰度发布
上下文透传

7.2 Gateway 工作原理

核心组件:

text
Route 路由
Predicate 断言
Filter 过滤器

请求流程:

text
客户端请求

Gateway Handler Mapping

匹配 Route

执行 GlobalFilter

执行 GatewayFilter

转发到下游服务

下游服务响应

执行响应过滤器

返回客户端

7.3 Route 路由

Route 表示一条转发规则。

例如:

text
当请求路径以 /api/order 开头
转发到 order-service

7.4 Predicate 断言

Predicate 用来判断请求是否匹配路由。

常见断言:

text
Path
Method
Header
Query
Cookie
Host
After
Before
Between

例如:

yaml
predicates:
  - Path=/api/order/**

表示只有路径匹配 /api/order/** 才进入该路由。


7.5 Filter 过滤器

Filter 用来修改请求或响应。

常见功能:

text
添加请求头
删除请求头
路径重写
鉴权
日志
限流
跨域

7.6 Gateway 2025 版本依赖

Spring Cloud Gateway 2025 推荐使用新的 WebFlux starter:

xml
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-gateway-server-webflux</artifactId>
</dependency>

同时需要注册中心:

xml
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>

注意:

text
Gateway WebFlux 是响应式网关,不要引入 spring-boot-starter-web。
如果引入 servlet web,可能导致应用类型冲突。

7.7 gateway-service 配置

gateway-service/application.yml

yaml
server:
  port: 9000

spring:
  application:
    name: gateway-service

  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848

    gateway:
      server:
        webflux:
          discovery:
            locator:
              enabled: true

          routes:
            - id: order-route
              uri: lb://order-service
              predicates:
                - Path=/api/order/**
              filters:
                - StripPrefix=1

            - id: stock-route
              uri: lb://stock-service
              predicates:
                - Path=/api/stock/**
              filters:
                - StripPrefix=1

说明:

text
lb://order-service 表示通过服务名负载均衡调用 order-service。
Path=/api/order/** 表示匹配 /api/order 开头的请求。
StripPrefix=1 表示去掉第一段路径 /api。

访问:

text
http://localhost:9000/api/order/order/create?productId=1001&count=2

经过 StripPrefix=1 后转发到:

text
http://order-service/order/create?productId=1001&count=2

7.8 Gateway 旧配置和新配置注意

在 Spring Cloud Gateway 2025 版本中,WebFlux Gateway 的新属性前缀建议使用:

yaml
spring:
  cloud:
    gateway:
      server:
        webflux:
          routes:
            - id: order-route
              uri: lb://order-service
              predicates:
                - Path=/api/order/**

旧版本常见写法是:

yaml
spring:
  cloud:
    gateway:
      routes:
        - id: order-route
          uri: lb://order-service
          predicates:
            - Path=/api/order/**

复习时要注意:

text
Spring Cloud 2025 中 Gateway 模块命名和属性前缀发生过调整。
新项目建议使用新 starter 和新前缀。

7.9 Gateway 启动类

java
package com.demo.gateway;

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

@SpringBootApplication
public class GatewayServiceApplication {

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

7.10 Gateway 全局过滤器

自定义全局日志过滤器:

java
package com.demo.gateway.filter;

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

@Component
public class AccessLogGlobalFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange,
                             GatewayFilterChain chain) {

        String path = exchange.getRequest().getURI().getPath();
        String method = exchange.getRequest().getMethod().name();

        long start = System.currentTimeMillis();

        return chain.filter(exchange)
                .then(Mono.fromRunnable(() -> {
                    long cost = System.currentTimeMillis() - start;
                    System.out.println("[Gateway AccessLog] "
                            + method + " " + path + ", cost=" + cost + "ms");
                }));
    }

    @Override
    public int getOrder() {
        return -100;
    }
}

7.11 Gateway 跨域配置

yaml
spring:
  cloud:
    gateway:
      server:
        webflux:
          globalcors:
            cors-configurations:
              '[/**]':
                allowedOrigins:
                  - "http://localhost:5173"
                  - "http://localhost:3000"
                allowedMethods:
                  - GET
                  - POST
                  - PUT
                  - DELETE
                  - OPTIONS
                allowedHeaders:
                  - "*"
                allowCredentials: true

7.12 Gateway 路径重写

示例:

yaml
spring:
  cloud:
    gateway:
      server:
        webflux:
          routes:
            - id: order-route
              uri: lb://order-service
              predicates:
                - Path=/api/order/**
              filters:
                - RewritePath=/api/order/(?<segment>.*), /order/${segment}

访问:

text
/api/order/create

转发为:

text
/order/create

7.13 Gateway 和 Nacos 动态路由

基础课程中可以先使用 application.yml 静态路由。

生产中可以把路由配置放到 Nacos:

text
gateway-routes-dev.yml

然后通过配置中心动态刷新路由。

简单理解:

text
路由规则不写死在项目里,而是放在配置中心管理。

Released under the MIT License.