Spring Cloud Gateway Documentation

repository·main·Indexed 26 days ago

https://github.com/spring-cloud/spring-cloud-gateway

A routing client for building API Gateways on Spring Framework, Spring Boot, and Project Reactor. It supports two flavors: a full-featured Server variant and a Proxy Exchange variant for annotation-based WebFlux or Web MVC applications. Key features include dynamic routing, predicate-based matching, request/response filters, and an Actuator endpoint for managing routes, global filters, and route filters.

Tokens
80K
Snippets
199
Records
285
Agent score
89%

What's inside Spring Cloud Gateway

  1. Overview of Spring Cloud Gateway flavors

    main

    Spring Cloud Gateway provides an API Gateway built on the Spring Ecosystem (Spring Framework 7, Spring Boot 4, and Project Reactor) to route to APIs and handle cross-cutting concerns like security, monitoring/metrics, and resiliency. It is available in two distinct flavors:

    1. Server variant: A full-featured API gateway that can run as a standalone application or be embedded within a Spring Boot application. It offers compatibility with both WebFlux and Web MVC.
    2. Proxy Exchange variant: Designed exclusively for use in annotation-based WebFlux or Web MVC applications. It allows you to use a special ProxyExchange object as a parameter in a web handler method.
  2. Overview of Spring Cloud Gateway features

    main

    Spring Cloud Gateway is a routing engine built on top of Spring Framework 5, Spring Boot 3, and Spring WebFlux. It provides the following core capabilities:

    • Dynamic Routing: Routes can be configured via API or configuration files.
    • Route Matching: Built into Spring Handler Mapping, allowing matching based on HTTP Request attributes such as Path, Method, Header, and Host.
    • Filters: Scoped to matching routes, filters can modify downstream HTTP requests and responses (e.g., adding/removing headers or parameters, rewriting paths, setting paths, or implementing circuit breakers).
    • Service Discovery Integration: Supports Spring Cloud DiscoveryClient for configuring routes dynamically based on registered services.

    Requirements:

    • Java 17
    • Spring Framework 6
    • Spring Boot 3
  3. Understand the Spring Cloud Gateway request lifecycle

    main

    Spring Cloud Gateway processes requests through a specific sequence of components:

    1. Gateway Handler Mapping: Determines if an incoming client request matches any defined routes.
    2. Gateway Web Handler: If a match is found, this handler manages the request execution.
    3. Filter Chain: The handler executes a chain of filters specific to the matched route. Filters are categorized into two phases:
      • pre filters: Logic executed before the proxy request is sent to the downstream service.
      • Proxy Request: The actual forwarding of the request to the target URI.
      • post filters: Logic executed after the proxy request has been made and the response is received.
  4. Runtime requirements for Spring Cloud Gateway

    main

    Spring Cloud Gateway is built on Spring Boot, Spring WebFlux, and Project Reactor.

    Critical Constraints:

    • It requires the Netty runtime provided by Spring Boot and Spring WebFlux.
    • It does not work in a traditional Servlet Container.
    • It does not work when packaged as a WAR file.
    • Because it is reactive, many synchronous libraries (such as standard Spring Data or Spring Security patterns) may not apply. You should familiarize yourself with reactive programming concepts before use.
  5. Features of Spring Cloud Gateway

    main

    Spring Cloud Gateway provides several core capabilities for API routing and cross-cutting concerns:

    • Framework Support: Built on Spring Framework and Spring Boot; compatible with both Spring WebFlux and Spring Web MVC.
    • Routing: Able to match routes on any request attribute.
    • Granularity: Predicates and filters are specific to routes.
    • Resiliency: Integration with Spring Cloud Circuit Breaker.
    • Service Discovery: Integration with Spring Cloud DiscoveryClient.
    • Traffic Management: Request Rate Limiting and Path Rewriting.
    • Extensibility: Easy to write custom Predicates and Filters.
  6. Spring Cloud Gateway Features

    main

    Spring Cloud Gateway is a client library for building API Gateways on Spring Framework 6 and Spring Boot 3. Key features include:

    • Java 17 compatibility.
    • Dynamic routing and route matching built into Spring Handler Mapping.
    • HTTP Request matching based on Path, Method, Header, Host, etc.
    • Scoped Filters: Filters can be scoped to matching routes and can modify downstream HTTP Requests and HTTP Responses (e.g., Add/Remove Headers, Add/Remove Parameters, Rewrite Path, Set Path, Circuit Breaker, etc.).
    • Configuration Flexibility: Supports both API-driven and configuration-driven approaches.
    • Service Discovery Integration: Supports Spring Cloud DiscoveryClient for configuring routes.
  7. Understand GatewayFilter Factories

    main

    Spring Cloud Gateway provides GatewayFilter factories that allow you to modify incoming HTTP requests or outgoing HTTP responses. These filters are scoped to a specific route.

    To see detailed implementation examples and usage patterns for the built-in filters, you can examine the unit tests in the spring-cloud-gateway-server-webflux module.

    https://github.com/spring-cloud/spring-cloud-gateway/tree/main/spring-cloud-gateway-server-webflux/src/test/java/org/springframework/cloud/gateway/filter/factory
  8. Understand Spring Cloud Gateway WebMvc core concepts

    main

    The WebMvc-based Spring Cloud Gateway is built around three primary concepts:

    • Route: The fundamental building block. A route consists of an ID, a destination URI, a collection of predicates, and a collection of filters. A route is considered a match only if the aggregate of its predicates evaluates to true.
    • Predicate: Uses Spring WebMvc.fn RequestPredicate. It takes a ServerRequest as input and allows matching based on HTTP request attributes such as headers, parameters, or paths.
    • Filter: Uses Spring WebMvc.fn HandlerFilterFunction. Filters allow you to modify requests and responses.
      • 'Before' filters: Can implement Function<ServerRequest, ServerRequest> and be adapted using HandlerFilterFunction.ofRequestProcessor().
      • 'After' filters: Can implement BiFunction<ServerRequest, T extends ServerResponse, R extends ServerResponse> and be adapted using HandlerFilterFunction.ofResponseProcessor().
  9. Understand Spring Cloud Gateway Server MVC Architecture

    main

    Spring Cloud Gateway Server MVC is built on top of the Spring WebMvc functional API (WebMvc.fn). Routes are defined as standard RouterFunction instances.

    Key architectural components include:

    • Routing: Uses special HandlerFunction implementations from org.springframework.cloud.gateway.server.mvc.handler.HandlerFunctions to forward HTTP requests.
    • Predicates: Uses RequestPredicate implementations found in org.springframework.cloud.gateway.server.mvc.predicate.GatewayRequestPredicates to match incoming requests.
    • Filters: Uses HandlerFilterFunctions found in org.springframework.cloud.gateway.server.mvc.filter.FilterFunctions.
      • Before Filters: Implemented as request processors via org.springframework.cloud.gateway.server.mvc.filter.BeforeFilterFunctions.
      • After Filters: Implemented as response processors via org.springframework.cloud.gateway.server.mvc.filter.AfterFilterFunctions.

    Important Note: Any path defined on a route URI will be ignored.

  10. Understand Spring Cloud Gateway core concepts

    main

    Spring Cloud Gateway is built around three primary concepts used to manage and route traffic:

    • Route: The fundamental building block. A route consists of an ID, a destination URI, a collection of Predicates, and a collection of Filters. A route is considered a match only if the aggregate of its predicates evaluates to true.
    • Predicate: A condition used to match an incoming HTTP request. It takes a ServerWebExchange as input, allowing you to match requests based on attributes like headers, parameters, paths, or methods.
    • Filter: A component used to intercept and modify the request or response. Filters are instances of GatewayFilter that can be applied to a route to change the request before it is sent downstream, or modify the response after it is received from the downstream service.
  11. Configure and use the Version Route Predicate Factory

    main

    Matches requests based on API versioning extracted via Spring WebFlux's ApiVersionStrategy.

    1. Configure Version Resolution

    You must define how to extract the version (e.g., from a header, query parameter, or path segment) using spring.webflux.apiversion.use.*.

    2. Use the Version Predicate

    • Fixed version (Version=1.3): Matches only if the resolved version equals 1.3 exactly.
    • Baseline version (Version=1.1+): Matches if the resolved version is greater than or equal to 1.1.
    # 1. Configure strategy
    spring:
      webflux:
        apiversion:
          use:
            header: X-API-Version
            query-parameter: apiVersion
            path-segment: 1 # /v1/users -> version = "1"
    
    # 2. Use in routes
    spring:
      cloud:
        gateway:
          server:
            webflux:
              routes:
              - id: version_11_plus_route
                uri: https://example.org
                predicates:
                - Path=/api/**
                - Version=1.1+
  12. Write Custom GatewayFilter Factories

    main

    To create a custom GatewayFilter, implement the GatewayFilterFactory interface as a Spring bean. You can extend AbstractGatewayFilterFactory<C> for convenience.

    • Pre-filters: Manipulate the ServerHttpRequest using a builder before calling chain.filter(exchange).
    • Post-filters: Call chain.filter(exchange) and use .then() to execute logic on the ServerHttpResponse after the filter chain has processed the request.
    // Pre-filter example
    @Component
    public class PreGatewayFilterFactory extends AbstractGatewayFilterFactory<PreGatewayFilterFactory.Config> {
    
        public PreGatewayFilterFactory() {
            super(Config.class);
        }
    
        @Override
        public GatewayFilter apply(Config config) {
            return (exchange, chain) -> {
                ServerHttpRequest.Builder builder = exchange.getRequest().mutate();
                return chain.filter(exchange.mutate().request(builder.build()).build());
            };
        }
    
        public static class Config {}
    }
    
    // Post-filter example
    @Component
    public class PostGatewayFilterFactory extends AbstractGatewayFilterFactory<PostGatewayFilterFactory.Config> {
    
        public PostGatewayFilterFactory() {
            super(Config.class);
        }
    
        @Override
        public GatewayFilter apply(Config config) {
            return (exchange, chain) -> {
                return chain.filter(exchange).then(Mono.fromRunnable(() -> {
                    ServerHttpResponse response = exchange.getResponse();
                    // Manipulate the response in some way
                }));
            };
        }
    
        public static class Config {}
    }