5.Gateway-新一代API网关服务

1.Gateway 简介

1.Spring Cloud Gateway基于Spring Boot 2.x,Spring WebFlux和Project Reactor构建。结果,当您使用Spring Cloud Gateway时,许多您熟悉的同步库(例如,Spring Data和Spring Security)和模式可能不适用。
2.Spring Cloud Gateway需要Spring Boot和Spring Webflux提供的Netty运行时。它不能在传统的Servlet容器中或作为WAR构建时使用
3.Spring Cloud Gateway项目不要引入spring web 包,以及webmvc

Spring Cloud Gateway 为 SpringBoot 应用提供了API网关支持,具有强大的智能路由与过滤器功能,本文将对其用法进行详细介绍。

Gateway是在Spring生态系统之上构建的API网关服务,基于Spring 5,Spring Boot 2和 Project Reactor等技术。Gateway旨在提供一种简单而有效的方式来对API进行路由,以及提供一些强大的过滤器功能, 例如:熔断、限流、重试等。

1.1 特性

Spring Cloud Gateway 具有如下特性:

  • 基于Spring Framework 5, Project Reactor 和 Spring Boot 2.0 进行构建;
  • 动态路由:能够匹配任何请求属性;
  • 可以对路由指定 Predicate(断言)和 Filter(过滤器);
  • 集成Hystrix的断路器功能;
  • 集成 Spring Cloud 服务发现功能;
  • 易于编写的 Predicate(断言)和 Filter(过滤器);
  • 请求限流功能;
  • 支持路径重写

1.2 相关概念

  • Route(路由):路由是构建网关的基本模块,它由ID,目标URI,一系列的断言和过滤器组成,如果断言为true则匹配该路由;
  • Predicate(断言):指的是Java 8 的 Function Predicate。 输入类型是Spring框架中的ServerWebExchange。 这使开发人员可以匹配HTTP请求中的所有内容,例如请求头或请求参数。如果请求与断言相匹配,则进行路由;
  • Filter(过滤器):指的是Spring框架中GatewayFilter的实例,使用过滤器,可以在请求被路由前后对请求进行修改。

2.创建 api-gateway模块

这里我们创建一个api-gateway模块来演示Gateway的常用功能。
不希望启用网关,请设置 spring.cloud.gateway.enabled=false

2.1 pom.xml添加依赖

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

2.2 使用yml配置(一)

Gateway 提供了两种不同的方式用于配置路由,一种是通过yml文件来配置,另一种是通过Java Bean来配置,下面我们分别介绍下。

注意:高优先级的路由最好放在低优先级前面

  • 在application.yml中进行配置:
server:
  port: 9201
service-url:
  user-service: http://localhost:8201
spring:
  cloud:
    gateway:
      routes:
        - id: path_route #路由的ID
          uri: ${service-url.user-service}/user/{id} #匹配后路由地址
          predicates: # 断言,路径相匹配的进行路由
            - Path=/user/{id}

  • 启动eureka-server,user-service和api-gateway服务,并调用该地址测试:http://localhost:9201/user/1
  • 我们发现该请求被路由到了user-service的该路径上:http://localhost:8201/user/1
    -yml配置

2.3使用Java Bean配置(二)

  • 添加相关配置类,并配置一个RouteLocator对象:
@Configuration
public class GatewayConfig {

    @Bean
    public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
        return builder.routes()
                .route("path_route2", r -> r.path("/user/getByUsername")
                        .uri("http://localhost:8201/user/getByUsername"))
                .build();
    }
}
  • 重新启动api-gateway服务,并调用该地址测试:http://localhost:9201/user/getByUsername?username=macro
  • 我们发现该请求被路由到了user-service的该路径上:http://localhost:8201/user/getByUsername?username=macro
    java配置

3.结合注册中心使用

3.1 使用动态路由

  • 在pom.xml中添加相关依赖
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
  • application.yml配置文件:
server:
  port: 9201
spring:
  application:
    name: api-gateway
  cloud:
    gateway:
      discovery:
        locator:
          enabled: true #开启从注册中心动态创建路由的功能
          lower-case-service-id: true #使用小写服务名,默认是大写
    nacos:
      discovery:
        server-addr: localhost:8848 #配置Nacos地址

logging:
  level:
    org.springframework.cloud.gateway: debug

  • 启动api-gateway服务,访问http://localhost:9201/user-service/user/1 ,可以路由到user-service的http://localhost:8201/user/1 处。

3.2 使用过滤器

在结合注册中心使用过滤器的时候,我们需要注意的是uri的协议为lb,这样才能启用Gateway的负载均衡功能。

  • 修改application.yml文件,使用了PrefixPath过滤器,会为所有GET请求路径添加/user路径并路由;
server:
  port: 9201
spring:
  application:
    name: api-gateway
  cloud:
    gateway:
      routes:
        - id: prefixpath_route
          uri: lb://user-service #此处需要使用lb协议
          predicates:
            - Method=GET
          filters:
            - PrefixPath=/user
      discovery:
        locator:
          enabled: true
eureka:
  client:
    service-url: 
      defaultZone: http://localhost:8001/eureka/
logging:
  level:
    org.springframework.cloud.gateway: debug

  • 使用application.yml配置文件启动api-gateway服务,访问http://localhost:9201/1 ,可以路由到user-service的http://localhost:8201/user/1 处。

4.Route Predicate 的使用

  • Spring Cloud Gateway将路由匹配作为Spring WebFlux HandlerMapping基础架构的一部分。 Spring Cloud Gateway包括许多内置的Route Predicate工厂。 所有这些Predicate都与HTTP请求的不同属性匹配。 多个Route Predicate工厂可以进行组合,下面我们来介绍下一些常用的Route Predicate。
  • 有两种配置谓词和过滤器的方法:快捷方式和完全扩展的参数
快捷方式;快捷方式配置由过滤器名称识别,后跟一个等号(=),然后是由逗号分隔的参数值(,)。
spring:
  cloud:
    gateway:
      routes:
      - id: after_route
        uri: https://example.org
        predicates:
        - Cookie=mycookie,mycookievalue

完全扩展的参数看起来更像带有名称/值对的标准Yaml配置。通常,将有一个name键和一个args键。 args键是用于配置谓词或过滤器的键值对的映射。
spring:
  cloud:
    gateway:
      routes:
      - id: after_route
        uri: https://example.org
        predicates:
        - name: Cookie
          args:
            name: mycookie
            regexp: mycookievalue

4.1 After 在指定时间之后的请求会匹配该路由

spring:
  cloud:
    gateway:
      routes:
        - id: after_route
          uri: ${service-url.user-service}
          predicates:
            - After=2019-09-24T16:30:00+08:00[Asia/Shanghai]

4.2 Before 在指定时间之前的请求会匹配该路由

spring:
  cloud:
    gateway:
      routes:
        - id: before_route
          uri: ${service-url.user-service}
          predicates:
            - Before=2019-09-24T16:30:00+08:00[Asia/Shanghai]

4.3 Between 在指定时间区间内的请求会匹配该路由

spring:
  cloud:
    gateway:
      routes:
        - id: before_route
          uri: ${service-url.user-service}
          predicates:
            - Between=2019-09-24T16:30:00+08:00[Asia/Shanghai], 2019-09-25T16:30:00+08:00[Asia/Shanghai]

4.4 Cookie 带有指定Cookie的请求会匹配该路由

spring:
  cloud:
    gateway:
      routes:
        - id: cookie_route
          uri: ${service-url.user-service}
          predicates:
            - Cookie=username,macro
  • 使用curl工具发送带有cookie为username=macro的请求可以匹配该路由。
curl http://localhost:9201/user/1 --cookie "username=macro"

4.5 Header 带有指定请求头的请求会匹配该路由

spring:
  cloud:
    gateway:
      routes:
      - id: header_route
        uri: ${service-url.user-service}
        predicates:
        - Header=X-Request-Id, \d+

使用curl工具发送带有请求头为X-Request-Id:123的请求可以匹配该路由
curl http://localhost:9201/user/1 -H “X-Request-Id:123”

4.6 Host 带有指定Host的请求会匹配该路由

spring:
  cloud:
    gateway:
      routes:
        - id: host_route
          uri: ${service-url.user-service}
          predicates:
            - Host=**.macrozheng.com

使用curl工具发送带有请求头为Host:www.macrozheng.com的请求可以匹配该路由。
curl http://localhost:9201/user/1 -H "Host:www.macrozheng.com" 

4.7 Method 发送指定方法的请求会匹配该路由

spring:
  cloud:
    gateway:
      routes:
      - id: method_route
        uri: ${service-url.user-service}
        predicates:
        - Method=GET

使用curl工具发送GET请求可以匹配该路由。
curl http://localhost:9201/user/1

使用curl工具发送POST请求无法匹配该路由。
curl -X POST http://localhost:9201/user/1

4.8 Path 发送指定路径的请求会匹配该路由

spring:
  cloud:
    gateway:
      routes:
        - id: path_route
          uri: ${service-url.user-service}/user/{id}
          predicates:
            - Path=/user/{id}

使用curl工具发送/user/1路径请求可以匹配该路由。
curl http://localhost:9201/user/1

使用curl工具发送/abc/1路径请求无法匹配该路由。
curl http://localhost:9201/abc/1

4.9 Query 带指定查询参数的请求可以匹配该路由

spring:
  cloud:
    gateway:
      routes:
      - id: query_route
        uri: ${service-url.user-service}/user/getByUsername
        predicates:
        - Query=username

使用curl工具发送带username=macro查询参数的请求可以匹配该路由。
curl http://localhost:9201/user/getByUsername?username=macro

使用curl工具发送带不带查询参数的请求无法匹配该路由。
curl http://localhost:9201/user/getByUsername

4.10 RemoteAddr 从指定远程地址发起的请求可以匹配该路由

spring:
  cloud:
    gateway:
      routes:
      - id: remoteaddr_route
        uri: ${service-url.user-service}
        predicates:
        - RemoteAddr=192.168.1.1/24

使用curl工具从192.168.1.1发起请求可以匹配该路由。
curl http://localhost:9201/user/1

4.11 Weight 使用权重来路由相应请求

使用权重来路由相应请求,以下表示有80%的请求会被路由到localhost:8201,20%会被路由到localhost:8202。

spring:
  cloud:
    gateway:
      routes:
      - id: weight_high
        uri: http://localhost:8201
        predicates:
        - Weight=group1, 8
      - id: weight_low
        uri: http://localhost:8202
        predicates:
        - Weight=group1, 2

5.Route Filter 的使用

路由过滤器可用于修改进入的HTTP请求和返回的HTTP响应,路由过滤器只能指定路由进行使用。Spring Cloud Gateway 内置了多种路由过滤器,他们都由GatewayFilter的工厂类来产生,下面我们介绍下常用路由过滤器的用法。

5.1 AddRequestParameter 给请求添加参数

spring:
  cloud:
    gateway:
      routes:
        - id: add_request_parameter_route
          uri: http://localhost:8201
          filters:
            - AddRequestParameter=username, macro
          predicates:
            - Method=GET

以上配置会对GET请求添加username=macro的请求参数,通过curl工具使用以下命令进行测试。
curl http://localhost:9201/user/getByUsername
相当于发起该请求:
curl http://localhost:8201/user/getByUsername?username=macro

spring:
  cloud:
    gateway:
      routes:
      - id: add_request_parameter_route
        uri: https://example.org
        predicates:
        - Host: {segment}.myhost.org
        filters:
        - AddRequestParameter=foo, bar-{segment}

5.2 StripPrefix 对指定数量的路径前缀进行去除

spring:
  cloud:
    gateway:
      routes:
      - id: strip_prefix_route
        uri: http://localhost:8201
        predicates:
        - Path=/user-service/**
        filters:
        - StripPrefix=2

以上配置会把以/user-service/开头的请求的路径去除两位,通过curl工具使用以下命令进行测试。
curl http://localhost:9201/user-service/a/user/1
相当于发起该请求:
curl http://localhost:8201/user/1

5.3 PrefixPath 对原有路径进行添加

spring:
  cloud:
    gateway:
      routes:
      - id: prefix_path_route
        uri: http://localhost:8201
        predicates:
        - Method=GET
        filters:
        - PrefixPath=/user

以上配置会对所有GET请求添加/user路径前缀,通过curl工具使用以下命令进行测试。
curl http://localhost:9201/1

相当于发起该请求:
curl http://localhost:8201/user/1

5.4 Hystrix 提供服务降级处理

  • Hystrix 过滤器允许你将断路器功能添加到网关路由中,使你的服务免受级联故障的影响,并提供服务降级处理。
  • 要开启断路器功能,我们需要在pom.xml中添加Hystrix的相关依赖:
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
  • 然后添加相关服务降级的处理类:

@RestController
public class FallbackController {

    @GetMapping("/fallback")
    public Object fallback() {
        Map<String,Object> result = new HashMap<>();
        result.put("data",null);
        result.put("message","Get request fallback!");
        result.put("code",500);
        return result;
    }
}
  • 在application-filter.yml中添加相关配置,当路由出错时会转发到服务降级处理的控制器上:
spring:
  cloud:
    gateway:
      routes:
        - id: hystrix_route
          uri: http://localhost:8201
          predicates:
            - Method=GET
          filters:
            - name: Hystrix
              args:
                name: fallbackcmd
                fallbackUri: forward:/fallback
  • 关闭user-service,调用该地址进行测试:http://localhost:9201/user/1 ,发现已经返回了服务降级的处理信息。
    服务降级

5.5 RequestRateLimiter 用于限流

RequestRateLimiter 过滤器可以用于限流,使用RateLimiter实现来确定是否允许当前请求继续进行,如果请求太大默认会返回HTTP 429-太多请求状态。

在pom.xml中添加相关依赖
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis-reactive</artifactId>
</dependency>
  • 添加限流策略的配置类,这里有两种策略一种是根据请求参数中的username进行限流,另一种是根据访问IP进行限流;

@Configuration
public class RedisRateLimiterConfig {
    @Bean
    KeyResolver userKeyResolver() {
        return exchange -> Mono.just(exchange.getRequest().getQueryParams().getFirst("username"));
    }

    @Bean
    public KeyResolver ipKeyResolver() {
        return exchange -> Mono.just(exchange.getRequest().getRemoteAddress().getHostName());
    }
}
  • 我们使用Redis来进行限流,所以需要添加Redis和RequestRateLimiter的配置,这里对所有的GET请求都进行了按IP来限流的操作;
server:
  port: 9201
spring:
  redis:
    host: localhost
    password: 123456
    port: 6379
  cloud:
    gateway:
      routes:
        - id: requestratelimiter_route
          uri: http://localhost:8201
          filters:
            - name: RequestRateLimiter
              args:
                redis-rate-limiter.replenishRate: 1 #每秒允许处理的请求数量
                redis-rate-limiter.burstCapacity: 2 #每秒最大处理的请求数量
                key-resolver: "#{@ipKeyResolver}" #限流策略,对应策略的Bean
          predicates:
            - Method=GET
logging:
  level:
    org.springframework.cloud.gateway: debug
  • 多次请求该地址:http://localhost:9201/user/1 ,会返回状态码为429的错误;
    429

5.6 Retry 重试的过滤器

  • 对路由请求进行重试的过滤器,可以根据路由请求返回的HTTP状态码来确定是否进行重试。
spring:
  cloud:
    gateway:
      routes:
      - id: retry_route
        uri: http://localhost:8201
        predicates:
        - Method=GET
        filters:
        - name: Retry
          args:
            retries: 1 #需要进行重试的次数
            statuses: BAD_GATEWAY #返回哪个状态码需要进行重试,返回状态码为5XX进行重试
            backoff:
              firstBackoff: 10ms
              maxBackoff: 50ms
              factor: 2
              basedOnPreviousValue: false
  • 当调用返回500时会进行重试,访问测试地址:http://localhost:9201/user/111
  • 可以发现user-service控制台报错2次,说明进行了一次重试。

5.7 AddRequestHeader 给请求头添加参数

spring:
  cloud:
    gateway:
      routes:
      - id: add_request_header_route
        uri: https://example.org
        filters:
        - AddRequestHeader=X-Request-red, blue

此清单将X-Request-red:blue标头添加到所有匹配请求的下游请求标头中。
AddRequestHeader知道用于匹配路径或主机的URI变量。 URI变量可以在值中使用,并在运行时扩展。
下面的示例配置使用变量的AddRequestHeader GatewayFilter:

spring:
  cloud:
    gateway:
      routes:
      - id: add_request_header_route
        uri: https://example.org
        predicates:
        - Path=/red/{segment}
        filters:
        - AddRequestHeader=X-Request-Red, Blue-{segment}

5.8 AddResponseHeader 响应头添加

spring:
  cloud:
    gateway:
      routes:
      - id: add_response_header_route
        uri: https://example.org
        predicates:
        - Host: {segment}.myhost.org
        filters:
        - AddResponseHeader=foo, bar-{segment}

5.9 DedupeResponseHeader 删除重复数据响应头

spring:
  cloud:
    gateway:
      routes:
      - id: dedupe_response_header_route
        uri: https://example.org
        filters:
        - DedupeResponseHeader=Access-Control-Allow-Credentials Access-Control-Allow-Origin

当网关CORS逻辑和下游逻辑都将它们添加时,这将删除Access-Control-Allow-Credentials和Access-Control-Allow-Origin响应标头的重复值。
DedupeResponseHeader过滤器还接受可选的策略参数(strategy)。接受的值为RETAIN_FIRST(默认值),RETAIN_LAST和RETAIN_UNIQUE。

5.10 MapRequestHeader 映射请求头

它创建一个新的命名头(toHeader),然后从传入的HTTP请求中将其值从现有的命名头(fromHeader)中提取出来。
如果输入标头不存在,则过滤器不起作用。如果新的命名报头已经存在,则其值将使用新值进行扩充
spring:
  cloud:
    gateway:
      routes:
      - id: map_request_header_route
        uri: https://example.org
        filters:
        - MapRequestHeader=Blue, X-Request-Red

这会将X-Request-Red:<values>标头添加到下游请求中,并带有来自传入HTTP请求的Blue标头的新值。

5.11 RedirectTo 重定向

RedirectTo GatewayFilter工厂采用两个参数,即status和url。 
status参数应该是300系列重定向HTTP代码,例如301。
url参数应该是有效的URL。这是Location标头的值。对于相对重定向,您应该使用uri:no:// op作为路由定义的uri

spring:
  cloud:
    gateway:
      routes:
      - id: prefixpath_route
        uri: https://example.org
        filters:
        - RedirectTo=302, https://acme.org

这将发送带有Location:https://acme.org标头的状态302以执行重定向。

5.12 RemoveRequestHeader 删除请求头参数


spring:
  cloud:
    gateway:
      routes:
      - id: removerequestheader_route
        uri: https://example.org
        filters:
        - RemoveRequestHeader=X-Request-Foo #它是要删除的标题的名称

这将删除X-Request-Foo标头,然后将其发送到下游。

5.13 RemoveResponseHeader 删除响应头参数

spring:
  cloud:
    gateway:
      routes:
      - id: removeresponseheader_route
        uri: https://example.org
        filters:
        - RemoveResponseHeader=X-Response-Foo

这将从响应中删除X-Response-Foo标头,然后将其返回到网关客户端。 

要删除任何类型的敏感标头,应为可能要为其配置的任何路由配置此过滤器。另外,您可以使用spring.cloud.gateway.default-filters一次配置此过滤器,并将其应用于所有路由。

5.14 RemoveRequestParameter 删除请求参数

spring:
  cloud:
    gateway:
      routes:
      - id: removerequestparameter_route
        uri: https://example.org
        filters:
        - RemoveRequestParameter=red

这将删除参数red,然后再将其发送到下游。

5.15 RewritePath 重写路径~

采用路径regexp参数和替换参数。这使用Java正则表达式提供了一种灵活的方式来重写请求路径

spring:
  cloud:
    gateway:
      routes:
      - id: rewritepath_route
        uri: https://example.org
        predicates:
        - Path=/red/**
        filters:
        - RewritePath=/red(?<segment>/?.*), $\{segment}

对于/red/blue的请求路径,这会在发出下游请求之前将路径设置为/blue。请注意,由于YAML规范,应将$替换为$\。

5.16 RewriteResponseHeader 替换响应头参数

采用名称/正则表达式替换参数。它使用Java正则表达式以灵活的方式重写响应标头值。

spring:
  cloud:
    gateway:
      routes:
      - id: rewriteresponseheader_route
        uri: https://example.org
        filters:
        - RewriteResponseHeader=X-Response-Red, , password=[^&]+, password=***
对于/42?user = ford&password = omg!what&flag = true的标头值,在发出下游请求后将其设置为/42?user = ford&password = ***&flag = true。由于YAML规范,必须使用$\表示$。

5.17 SaveSession 存储session

SaveSession GatewayFilter工厂在向下游转发呼叫之前强制执行WebSession :: save操作
当将诸如Spring Session之类的数据与惰性数据存储一起使用时,这特别有用,您需要确保在进行转发呼叫之前已保存会话状态

spring:
  cloud:
    gateway:
      routes:
      - id: save_session
        uri: https://example.org
        predicates:
        - Path=/foo/**
        filters:
        - SaveSession

如果您将Spring Security与Spring Session集成在一起,并想确保安全性详细信息已转发到远程进程,那么这一点至关重要。

5.18 SecureHeaders 安全响应头信息

SecureHeaders GatewayFilter工厂向响应添加了许多标头

添加了以下标头(以其默认值显示):
X-Xss-Protection:1 (mode=block)
Strict-Transport-Security (max-age=631138519)
X-Frame-Options (DENY)
X-Content-Type-Options (nosniff)
Referrer-Policy (no-referrer)
Content-Security-Policy (default-src 'self' https:; font-src 'self' https: data:; img-src 'self' https: data:; object-src 'none'; script-src https:; style-src 'self' https: 'unsafe-inline)'
X-Donload-Options (noopen)
X-Permitted-Cross-Domain-Policies (none)

要更改默认值,请在spring.cloud.gateway.filter.secure-headers命名空间中设置适当的属性。可以使用以下属性:
xss-protection-header
strict-transport-security
x-frame-options
x-content-type-options
referrer-policy
content-security-policy
x-download-options
x-permitted-cross-domain-policies

要禁用默认值,请设置spring.cloud.gateway.filter.secure-headers.disable属性,并用逗号分隔值。以下示例显示了如何执行此操作:
spring.cloud.gateway.filter.secure-headers.disable=x-frame-options,strict-transport-security

5.19 SetPath 访问路径设置

spring:
  cloud:
    gateway:
      routes:
      - id: setpath_route
        uri: https://example.org
        predicates:
        - Path=/red/{segment}
        filters:
        - SetPath=/{segment}

对于/red/blue的请求路径,这会在发出下游请求之前将路径设置为/blue。

5.20 SetRequestHeader 替换请求头参数

spring:
  cloud:
    gateway:
      routes:
      - id: setrequestheader_route
        uri: https://example.org
        filters:
        - SetRequestHeader=X-Request-Red, Blue

该GatewayFilter用给定名称替换(而不是添加)所有标头。因此,如果下游服务器响应X-Request-Red:1234,则将其替换为X-Request-Red:Blue,这是下游服务将收到的内容。

也可以动态替换
spring:
  cloud:
    gateway:
      routes:
      - id: setrequestheader_route
        uri: https://example.org
        predicates:
        - Host: {segment}.myhost.org
        filters:
        - SetRequestHeader=foo, bar-{segment}

5.21 SetResponseHeader 替换响应头参数

spring:
  cloud:
    gateway:
      routes:
      - id: setresponseheader_route
        uri: https://example.org
        filters:
        - SetResponseHeader=X-Response-Red, Blue

该GatewayFilter用给定名称替换(而不是添加)所有标头。因此,如果下游服务器使用X-Response-Red:1234进行响应,则将其替换为X-Response-Red:Blue,这是网关客户端将收到的内容。
动态替换参照请求头替换

5.22 SetStatus 设置状态码

SetStatus GatewayFilter工厂采用单个参数status。它必须是有效的Spring HttpStatus。
它可以是整数值404或枚举的字符串表示形式:NOT_FOUND。下面的清单配置一个SetStatus GatewayFilter:
spring:
  cloud:
    gateway:
      routes:
      - id: setstatusstring_route
        uri: https://example.org
        filters:
        - SetStatus=BAD_REQUEST
      - id: setstatusint_route
        uri: https://example.org
        filters:
        - SetStatus=401

无论哪种情况,响应的HTTP状态都设置为401。
您可以将SetStatus GatewayFilter配置为在响应的标头中从代理请求返回原始HTTP状态代码。如果使用以下属性配置标头,则会将其添加到响应中:
spring:
  cloud:
    gateway:
      set-status:
        original-status-header-name: original-http-status

5.23 RequestSize 请求大小过滤

  • 当请求大小大于允许的限制时,RequestSize GatewayFilter工厂可以限制请求到达下游服务。过滤器采用maxSize参数。 maxSize是一种DataSize类型,因此可以将值定义为一个数字,后跟一个可选的DataUnit后缀,例如’KB’或’MB’。字节的默认值为“ B”。它是请求的允许大小限制,以字节为单位。下面的清单配置一个RequestSize GatewayFilter:

spring:
  cloud:
    gateway:
      routes:
      - id: request_size_route
        uri: http://localhost:8080/upload
        predicates:
        - Path=/upload
        filters:
        - name: RequestSize
          args:
            maxSize: 5000000

当请求由于大小而被拒绝时,RequestSize GatewayFilter工厂将响应状态设置为413 Payload Too Large,并带有附加的报头errorMessage。以下示例显示了这样的errorMessage:
errorMessage` : `Request size is larger than permissible limit. Request size is 6.0 MB where permissible limit is 5.0 MB

5.24 SetRequestHost 设置请求host

在某些情况下,可能需要覆盖host header。在这种情况下,SetRequestHost GatewayFilter工厂可以用指定的值替换现有的host header。过滤器采用主机参数。
spring:
  cloud:
    gateway:
      routes:
      - id: set_request_host_header_route
        uri: http://localhost:8080/headers
        predicates:
        - Path=/headers
        filters:
        - name: SetRequestHost
          args:
            host: example.org
            
SetRequestHost GatewayFilter工厂用example.org替换主机头的值。

5.25 Default Filters 默认过滤器

要添加过滤器并将其应用于所有路由,可以使用spring.cloud.gateway.default-filters。
spring:
  cloud:
    gateway:
      default-filters:
      - AddResponseHeader=X-Response-Default-Red, Default-Blue
      - PrefixPath=/httpbin

6. CORS Configuration 跨域配置

您可以配置网关以控制CORS行为。 “全局” CORS配置是URL模式到Spring Framework CorsConfiguration的映射。以下示例配置了CORS:

spring:
  cloud:
    gateway:
      globalcors:
        cors-configurations:
          '[/**]':
            allowedOrigins: "https://docs.spring.io"
            allowedMethods:
            - GET

在前面的示例中,对于所有GET请求的路径,允许来自docs.spring.io的请求中的CORS请求。
要为未由某些网关路由谓词处理的请求提供相同的CORS配置,请将spring.cloud.gateway.globalcors.add-to-simple-url-handler-mapping属性设置为true。当您尝试支持CORS预检请求并且您的路由谓词未评估为true时,这很有用,因为HTTP方法是可选项。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值