RequestSize 过滤器

当请求大小超过允许的限制时,RequestSize 过滤器可以阻止请求到达下游服务。该过滤器接受一个 maxSize 参数。maxSizeDataSize 类型,因此值可以定义为一个数字后跟一个可选的 DataUnit 后缀,例如 'KB' 或 'MB'。默认单位是字节 ('B')。这是以字节为单位定义的请求允许的大小限制。以下配置展示了如何配置 RequestSize 过滤器

application.yml
spring:
  cloud:
    gateway:
      mvc:
        routes:
        - id: request_size_route
          uri: http://localhost:8080
          predicates:
          - Path=/upload
          filters:
          - name: RequestSize
            args:
              maxSize: 5000000
GatewaySampleApplication.java
import static org.springframework.cloud.gateway.server.mvc.filter.BeforeFilterFunctions.uri;
import static org.springframework.cloud.gateway.server.mvc.filter.BeforeFilterFunctions.requestSize;
import static org.springframework.cloud.gateway.server.mvc.handler.GatewayRouterFunctions.route;
import static org.springframework.cloud.gateway.server.mvc.handler.HandlerFunctions.http;

@Configuration
class RouteConfiguration {

    @Bean
    public RouterFunction<ServerResponse> gatewayRouterFunctionsRequestSize() {
        return route("request_size_route")
            .GET("/upload", http())
            .before(uri("http://localhost:8080"))
            .before(requestSize("5000000"))
            .build();
    }
}

当请求因大小而被拒绝时,RequestSize 过滤器将响应状态设置为 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
如果在路由定义中未提供过滤器参数,默认请求大小设置为五 MB。