### Request Rate Limiter Configuration Example Source: https://docs.spring.io/spring-cloud-gateway/reference/spring-cloud-gateway-server-webflux/gatewayfilter-factories/requestratelimiter-factory.html Configure the RequestRateLimiter filter in application.yml to set rate limiting rules. This example limits requests to 20 capacity, refills 10 tokens per second, with each request costing 1 token. ```yaml spring: cloud: gateway: routes: - id: requestratelimiter_route uri: https://example.org filters: - name: RequestRateLimiter args: bucket4j-rate-limiter.capacity: 20 bucket4j-rate-limiter.refillTokens: 10 bucket4j-rate-limiter.refillPeriod: 1s bucket4j-rate-limiter.requestedTokens: 1 ``` -------------------------------- ### Configure Method Route Predicate with Java Source: https://docs.spring.io/spring-cloud-gateway/reference/spring-cloud-gateway-server-webmvc/gateway-request-predicates.html Configure a route to match GET and POST HTTP methods using Java configuration. ```java import org.springframework.http.HttpMethod; import static org.springframework.cloud.gateway.server.mvc.filter.BeforeFilterFunctions.uri; import static org.springframework.cloud.gateway.server.mvc.handler.GatewayRouterFunctions.route; import static org.springframework.cloud.gateway.server.mvc.handler.HandlerFunctions.http; import static org.springframework.cloud.gateway.server.mvc.predicate.GatewayRequestPredicates.method; @Configuration class RouteConfiguration { @Bean public RouterFunction gatewayRouterFunctionsMethod() { return route("method_route") .route(method(HttpMethod.GET, HttpMethod.POST), http()) .before(uri("https://example.org")) .build(); } } ``` -------------------------------- ### Java Configuration for Weight Predicate Source: https://docs.spring.io/spring-cloud-gateway/reference/spring-cloud-gateway-server-webmvc/gateway-request-predicates.html Configure weight-based routing programmatically using Java. This example defines two routes with specific weights and paths. ```java import static org.springframework.cloud.gateway.server.mvc.filter.BeforeFilterFunctions.uri; import static org.springframework.cloud.gateway.server.mvc.handler.GatewayRouterFunctions.route; import static org.springframework.cloud.gateway.server.mvc.handler.HandlerFunctions.http; import static org.springframework.cloud.gateway.server.mvc.predicate.GatewayRequestPredicates.path; import static org.springframework.cloud.gateway.server.mvc.predicate.GatewayRequestPredicates.weight; @Configuration class RouteConfiguration { @Bean public RouterFunction gatewayRouterFunctionsWeights() { return route("weight_high") .route(weight("group1", 8).and(path("/**")), http()) .before(uri("https://weighthigh.org")) .build().and( route("weight_low") .route(weight("group1", 2).and(path("/**")), http()) .before(uri("https://weightlow.org")) .build()); } } ``` -------------------------------- ### Configure Method and Path Route Predicate with Java Source: https://docs.spring.io/spring-cloud-gateway/reference/spring-cloud-gateway-server-webmvc/gateway-request-predicates.html Configure a route to match a specific HTTP method (GET) and path (/mypath) using Java. ```java import static org.springframework.cloud.gateway.server.mvc.filter.BeforeFilterFunctions.uri; 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 gatewayRouterFunctionsMethodAndPath() { return route("method_and_path_route") .GET("/mypath", http()) .before(uri("https://example.org")) .build(); } } ``` -------------------------------- ### Forwarded Header Example Source: https://docs.spring.io/spring-cloud-gateway/reference/spring-cloud-gateway-server-webmvc/httpheadersfilters.html Example of a Forwarded header created by the Forwarded Headers Filter when the 'by' parameter is enabled. It includes proxy information, protocol, host, and the by-parameter with server address and port. ```text Forwarded: for="192.0.2.60:47011";proto=https;host="example.com:443";by="198.51.100.17:8080" ``` -------------------------------- ### Configure Method Route Predicate with YAML Source: https://docs.spring.io/spring-cloud-gateway/reference/spring-cloud-gateway-server-webmvc/gateway-request-predicates.html Configure a route to match GET and POST HTTP methods using application.yml. ```yaml spring: cloud: gateway: server: webmvc: routes: - id: method_route uri: https://example.org predicates: - Method=GET,POST ``` -------------------------------- ### YAML Configuration for Weight Predicate Source: https://docs.spring.io/spring-cloud-gateway/reference/spring-cloud-gateway-server-webmvc/gateway-request-predicates.html Configure weight-based routing in application.yml. This example sets up two routes with different weights for the same group. ```yaml spring: cloud: gateway: server: webmvc: routes: - id: weight_high uri: https://weighthigh.org predicates: - Weight=group1, 8 - id: weight_low uri: https://weightlow.org predicates: - Weight=group1, 2 ``` -------------------------------- ### Configure Path Route Predicate with YAML Source: https://docs.spring.io/spring-cloud-gateway/reference/spring-cloud-gateway-server-webmvc/gateway-request-predicates.html Configure a route to match paths starting with /red/ or /blue/ using application.yml. ```yaml spring: cloud: gateway: server: webmvc: routes: - id: path_route uri: https://example.org predicates: - Path=/red/{segment},/blue/{segment} ``` -------------------------------- ### Configure Query Route Predicate with Required Parameter Source: https://docs.spring.io/spring-cloud-gateway/reference/spring-cloud-gateway-server-webmvc/gateway-request-predicates.html This example shows how to configure a route that matches requests containing the 'green' query parameter using application.yml. ```yaml spring: cloud: gateway: server: webmvc: routes: - id: query_route uri: https://example.org predicates: - Query=green ``` -------------------------------- ### Define Routes with Fluent Java API Source: https://docs.spring.io/spring-cloud-gateway/reference/spring-cloud-gateway-server-webflux/fluent-java-routes-api.html This snippet demonstrates how to define multiple routes using the RouteLocatorBuilder's fluent API. It includes examples of host and path matching, adding response headers, and setting metadata. ```java import org.springframework.cloud.gateway.route.RouteLocator; import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder; import org.springframework.cloud.gateway.filter.ThrottleGatewayFilter; import org.springframework.context.annotation.Bean; import java.util.concurrent.TimeUnit; // static imports from GatewayFilters and RoutePredicates @Bean public RouteLocator customRouteLocator(RouteLocatorBuilder builder, ThrottleGatewayFilterFactory throttle) { return builder.routes() .route(r -> r.host("**.abc.org").and().path("/image/png") .filters(f -> f.addResponseHeader("X-TestHeader", "foobar")) .uri("http://httpbin.org:80") ) .route(r -> r.path("/image/webp") .filters(f -> f.addResponseHeader("X-AnotherHeader", "baz")) .uri("http://httpbin.org:80") .metadata("key", "value") ) .route(r -> r.order(-1) .host("**.throttle.org").and().path("/get") .filters(f -> f.filter(throttle.apply(1, 1, 10, TimeUnit.SECONDS))) .uri("http://httpbin.org:80") .metadata("key", "value") ) .build(); } ``` -------------------------------- ### Configure Query Route Predicate with Parameter and Regex Source: https://docs.spring.io/spring-cloud-gateway/reference/spring-cloud-gateway-server-webmvc/gateway-request-predicates.html This example configures a route that matches requests containing the 'red' query parameter with a value matching the 'gree.' regular expression, using application.yml. ```yaml spring: cloud: gateway: server: webmvc: routes: - id: query_route uri: https://example.org predicates: - Query=red, gree. ``` -------------------------------- ### Basic Route Definition with RouterFunctions.Builder Source: https://docs.spring.io/spring-cloud-gateway/reference/spring-cloud-gateway-server-webmvc/java-routes-api.html Defines a simple GET route using RouterFunctions.Builder. The route is configured to proxy requests to 'https://example.org'. ```java import static org.springframework.web.servlet.function.RouterFunctions.route; import static org.springframework.cloud.gateway.server.mvc.filter.BeforeFilterFunctions.uri; import static org.springframework.cloud.gateway.server.mvc.handler.HandlerFunctions.http; class SimpleGateway { @Bean public RouterFunction getRoute() { return route().GET("/get", http()) .before(uri("https://example.org")) .build(); } } ``` -------------------------------- ### Configure SetPath GatewayFilter in application.yml Source: https://docs.spring.io/spring-cloud-gateway/reference/spring-cloud-gateway-server-webflux/gatewayfilter-factories/setpath-factory.html This example demonstrates how to configure the SetPath GatewayFilter in an application.yml file. It defines a route with a specific path predicate and applies the SetPath filter to modify the request path before forwarding. ```yaml spring: cloud: gateway: routes: - id: setpath_route uri: https://example.org predicates: - Path=/red/{segment} filters: - SetPath=/{segment} ``` -------------------------------- ### Configure PrefixPath Filter in YAML Source: https://docs.spring.io/spring-cloud-gateway/reference/spring-cloud-gateway-server-webmvc/filters/prefixpath.html Configure the PrefixPath filter using application.yml. This example sets a route with ID 'prefixpath_route' that forwards requests to 'https://example.org' and prefixes the request path with '/mypath'. ```yaml spring: cloud: gateway: server: webmvc: routes: - id: prefixpath_route uri: https://example.org predicates: - Path=/** filters: - PrefixPath=/mypath ``` -------------------------------- ### Configure PrefixPath Filter in Java Source: https://docs.spring.io/spring-cloud-gateway/reference/spring-cloud-gateway-server-webmvc/filters/prefixpath.html Configure the PrefixPath filter using Java code. This example defines a RouterFunction that creates a route with ID 'prefixpath_route', forwards requests to 'https://example.org', and prefixes the request path with '/mypath'. ```java import static org.springframework.cloud.gateway.server.mvc.filter.BeforeFilterFunctions.uri; import static org.springframework.cloud.gateway.server.mvc.filter.BeforeFilterFunctions.prefixPath; 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 gatewayRouterFunctionsPrefixPath() { return route("prefixpath_route") .GET("/**", http()) .before(uri("https://example.org")) .before(prefixPath("/mypath")) .build(); } } ``` -------------------------------- ### Custom Global Pre-Filter Source: https://docs.spring.io/spring-cloud-gateway/reference/spring-cloud-gateway-server-webflux/developer-guide.html Implement a global pre-filter to modify outgoing requests. This example adds a custom request header with the user's name. ```java @Bean public GlobalFilter customGlobalFilter() { return (exchange, chain) -> exchange.getPrincipal() .map(Principal::getName) .defaultIfEmpty("Default User") .map(userName -> { //adds header to proxied request ServerHttpRequest.Builder builder = exchange.getRequest().mutate().header("CUSTOM-REQUEST-HEADER", userName); //use builder to manipulate the request return exchange.mutate().request(builder.build()).build(); }) .flatMap(chain::filter); } ``` -------------------------------- ### Configure MapRequestHeader Filter Source: https://docs.spring.io/spring-cloud-gateway/reference/spring-cloud-gateway-server-webflux/gatewayfilter-factories/maprequestheader-factory.html This example shows how to configure the MapRequestHeader filter in application.yml to map the 'Blue' header to 'X-Request-Red'. If the 'Blue' header is not present, the filter has no effect. If 'X-Request-Red' already exists, its values are augmented. ```yaml spring: cloud: gateway: routes: - id: map_request_header_route uri: https://example.org filters: - MapRequestHeader=Blue, X-Request-Red ``` -------------------------------- ### Redis RateLimiter Configuration Source: https://docs.spring.io/spring-cloud-gateway/reference/spring-cloud-gateway-server-webflux/gatewayfilter-factories/requestratelimiter-factory.html Configures the Redis-based RateLimiter with specific replenish rate, burst capacity, and requested tokens. This example sets a limit of 10 requests per user per second, with a burst capacity of 20. ```yaml spring: cloud: gateway: routes: - id: requestratelimiter_route uri: https://example.org filters: - name: RequestRateLimiter args: redis-rate-limiter.replenishRate: 10 redis-rate-limiter.burstCapacity: 20 redis-rate-limiter.requestedTokens: 1 ``` -------------------------------- ### Get Gateway Route Filters Source: https://docs.spring.io/spring-cloud-gateway/reference/spring-cloud-gateway-server-webflux/actuator-api.html Retrieve the GatewayFilter factories applied to routes by making a GET request to the /actuator/gateway/routefilters endpoint. The response lists the filters and their configurations. ```shell GET /actuator/gateway/routefilters ``` -------------------------------- ### Equivalent Retry configurations using shortcut notation Source: https://docs.spring.io/spring-cloud-gateway/reference/spring-cloud-gateway-server-webflux/gatewayfilter-factories/retry-factory.html Demonstrates two equivalent ways to configure the Retry GatewayFilter: one with detailed arguments and another using a simplified shortcut notation. The shortcut is useful for common retry scenarios. ```yaml spring: cloud: gateway: routes: - id: retry_route uri: https://example.org filters: - name: Retry args: retries: 3 statuses: INTERNAL_SERVER_ERROR methods: GET backoff: firstBackoff: 10ms maxBackoff: 50ms factor: 2 basedOnPreviousValue: false jitter: randomFactor: 0.5 timeout: 100ms ``` ```yaml spring: cloud: gateway: routes: - id: retryshortcut_route uri: https://example.org filters: - Retry=3,INTERNAL_SERVER_ERROR,GET,10ms,50ms,2,false,0.5,100ms ``` -------------------------------- ### Get All Defined Gateway Routes Source: https://docs.spring.io/spring-cloud-gateway/reference/spring-cloud-gateway-server-webflux/actuator-api.html Retrieve all routes defined in the gateway by making a GET request to the /actuator/gateway/routes endpoint. The response provides details for each route, including its ID, predicate, filters, and order. ```shell GET /actuator/gateway/routes ``` -------------------------------- ### Get Specific Gateway Route Information Source: https://docs.spring.io/spring-cloud-gateway/reference/spring-cloud-gateway-server-webflux/actuator-api.html Retrieve information about a single route by making a GET request to /actuator/gateway/routes/{id}, replacing {id} with the route's ID. The response includes the route's ID, predicates, filters, URI, and order. ```shell GET /actuator/gateway/routes/first_route ``` -------------------------------- ### Gateway Route Configuration with Named and Shortcut Filters Source: https://docs.spring.io/spring-cloud-gateway/reference/spring-cloud-gateway-server-webflux/configuration.html Demonstrates equivalent Spring Cloud Gateway route configurations using both named arguments and shortcut notation for filters. ```yaml spring: cloud: gateway: routes: - id: setstatus_route uri: https://example.org filters: - name: SetStatus args: status: 401 - id: setstatusshortcut_route uri: https://example.org filters: - SetStatus=401 ``` -------------------------------- ### Get Route by ID Source: https://docs.spring.io/spring-cloud-gateway/reference/spring-cloud-gateway-server-webflux/actuator-api.html Displays information about a particular route. ```APIDOC ## GET /actuator/gateway/routes/{id} ### Description Displays information about a particular route. ### Method GET ### Endpoint /actuator/gateway/routes/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the route to retrieve. ``` -------------------------------- ### Configure Path Route Predicate with Java Source: https://docs.spring.io/spring-cloud-gateway/reference/spring-cloud-gateway-server-webmvc/gateway-request-predicates.html Configure a route to match paths /red/{segment} or /blue/{segment} using Java. ```java import static org.springframework.cloud.gateway.server.mvc.filter.BeforeFilterFunctions.uri; import static org.springframework.cloud.gateway.server.mvc.handler.GatewayRouterFunctions.route; import static org.springframework.cloud.gateway.server.mvc.handler.HandlerFunctions.http; import static org.springframework.cloud.gateway.server.mvc.predicate.GatewayRequestPredicates.path; @Configuration class RouteConfiguration { @Bean public RouterFunction gatewayRouterFunctionsPath() { return route("path_route") .route(path("/red/{segment}", "/blue/{segment}"), http()) .before(uri("https://example.org")) .build(); } } ``` -------------------------------- ### Get Specific Route Source: https://docs.spring.io/spring-cloud-gateway/reference/spring-cloud-gateway-server-webflux/actuator-api.html Retrieves detailed information about a single route identified by its ID. ```APIDOC ## Retrieving Information about a Particular Route ### Description To retrieve information about a single route, make a `GET` request to `/actuator/gateway/routes/{id}`. ### Method GET ### Endpoint /actuator/gateway/routes/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the route to retrieve. ### Response #### Success Response (200) - **route_id** (String) - The route ID. - **predicate** (String) - The route predicate. - **filters** (Array) - The collection of filters applied to the route. - **uri** (String) - The destination URI of the route. - **order** (Number) - The route order. ### Response Example ```json { "route_id": "first_route", "predicate": "(Paths: [/first], match trailing slash: true && Methods: [GET])", "filters": [], "uri": "https://www.uri-destination.org", "order": 0 } ``` ``` -------------------------------- ### Get Routes Source: https://docs.spring.io/spring-cloud-gateway/reference/spring-cloud-gateway-server-webflux/actuator-api.html Retrieves all routes defined in the gateway, including their predicates, filters, and order. ```APIDOC ## Retrieving the Routes Defined in the Gateway ### Description To retrieve the routes defined in the gateway, make a `GET` request to `/actuator/gateway/routes`. ### Method GET ### Endpoint /actuator/gateway/routes ### Response #### Success Response (200) - **Array** - A JSON array where each element represents a route. - **route_id** (String) - The route ID. - **route_object.predicate** (Object) - The route predicate. - **route_object.filters** (Array) - The `GatewayFilter` factories applied to the route. - **order** (Number) - The route order. ### Response Example ```json [ { "route_id": "first_route", "route_object": { "predicate": "org.springframework.cloud.gateway.handler.predicate.PathRoutePredicateFactory$$Lambda$432/1736826640@1e9d7e7d", "filters": [ "OrderedGatewayFilter{delegate=org.springframework.cloud.gateway.filter.factory.PreserveHostHeaderGatewayFilterFactory$$Lambda$436/674480275@6631ef72, order=0}" ] }, "order": 0 }, { "route_id": "second_route", "route_object": { "predicate": "org.springframework.cloud.gateway.handler.predicate.PathRoutePredicateFactory$$Lambda$432/1736826640@cd8d298", "filters": [] }, "order": 0 } ] ``` ``` -------------------------------- ### Configure Before Predicate in Java Source: https://docs.spring.io/spring-cloud-gateway/reference/spring-cloud-gateway-server-webmvc/gateway-request-predicates.html Configure the Before route predicate programmatically using Java. Ensure necessary imports are included. ```java import java.time.ZonedDateTime; import static org.springframework.cloud.gateway.server.mvc.filter.BeforeFilterFunctions.uri; import static org.springframework.cloud.gateway.server.mvc.handler.GatewayRouterFunctions.route; import static org.springframework.cloud.gateway.server.mvc.handler.HandlerFunctions.http; import static org.springframework.cloud.gateway.server.mvc.predicate.GatewayRequestPredicates.before; @Configuration class RouteConfiguration { @Bean public RouterFunction gatewayRouterFunctionsBefore() { return route("before_route") .route(before(ZonedDateTime.parse("2017-01-20T17:42:47.789-07:00[America/Denver]")), http() .before(uri("https://example.org")) .build(); } } ``` -------------------------------- ### Extract URI Template Variables Source: https://docs.spring.io/spring-cloud-gateway/reference/spring-cloud-gateway-server-webmvc/gateway-request-predicates.html Example of how to extract URI template variables from a request using MvcUtils.getUriTemplateVariables. ```java Map uriVariables = MvcUtils.getUriTemplateVariables(request); String segment = uriVariables.get("segment"); ``` -------------------------------- ### Configure RemoveRequestParameter Filter Source: https://docs.spring.io/spring-cloud-gateway/reference/spring-cloud-gateway-server-webflux/gatewayfilter-factories/removerequestparameter-factory.html This example shows how to configure the RemoveRequestParameter filter in application.yml to remove the 'red' query parameter. ```yaml spring: cloud: gateway: routes: - id: removerequestparameter_route uri: https://example.org filters: - RemoveRequestParameter=red ``` -------------------------------- ### Configure DiscoveryClient Locator Predicates and Filters (Properties) Source: https://docs.spring.io/spring-cloud-gateway/reference/spring-cloud-gateway-server-webflux/the-discoveryclient-route-definition-locator.html Use this properties format to customize predicates and filters for DiscoveryClient routes. Ensure default functionality is included if needed. ```properties spring.cloud.gateway.discovery.locator.predicates[0].name=Path spring.cloud.gateway.discovery.locator.predicates[0].args[pattern]="'/'+serviceId+'/**'" spring.cloud.gateway.discovery.locator.predicates[1].name=Host spring.cloud.gateway.discovery.locator.predicates[1].args[pattern]="'**.foo.com'" spring.cloud.gateway.discovery.locator.filters[0].name=CircuitBreaker spring.cloud.gateway.discovery.locator.filters[0].args[name]=serviceId spring.cloud.gateway.discovery.locator.filters[1].name=RewritePath spring.cloud.gateway.discovery.locator.filters[1].args[regexp]="'/' + serviceId + '/?(?.*)'" spring.cloud.gateway.discovery.locator.filters[1].args[replacement]="'/${remaining}'" ``` -------------------------------- ### Get Route Filters Source: https://docs.spring.io/spring-cloud-gateway/reference/spring-cloud-gateway-server-webflux/actuator-api.html Retrieves the GatewayFilter factories applied to routes. The response lists the filter factories and their configuration details. ```APIDOC ## Get Route Filters ### Description To retrieve the `GatewayFilter` factories applied to routes, make a `GET` request to `/actuator/gateway/routefilters`. ### Method GET ### Endpoint /actuator/gateway/routefilters ### Response #### Success Response (200) - **Object** - A JSON object where keys are string representations of `GatewayFilter` factories and values are typically null. ### Response Example ```json { "[AddRequestHeaderGatewayFilterFactory@570ed9c configClass = AbstractNameValueGatewayFilterFactory.NameValueConfig]": null, "[SecureHeadersGatewayFilterFactory@fceab5d configClass = Object]": null, "[SaveSessionGatewayFilterFactory@4449b273 configClass = Object]": null } ``` ``` -------------------------------- ### Create a Route Definition Source: https://docs.spring.io/spring-cloud-gateway/reference/spring-cloud-gateway-server-webflux/actuator-api.html Create a new route definition by making a POST request to /gateway/routes/{id_route_to_create}. The request body should be a JSON object specifying the route's fields. ```shell POST /gateway/routes/{id_route_to_create} ``` -------------------------------- ### Configure DiscoveryClient Locator Predicates and Filters (YAML) Source: https://docs.spring.io/spring-cloud-gateway/reference/spring-cloud-gateway-server-webflux/the-discoveryclient-route-definition-locator.html Use this YAML format to customize predicates and filters for DiscoveryClient routes. Ensure default functionality is included if needed. ```yaml spring: cloud: gateway: discovery: locator: predicates: - name: Host args: pattern: "'**.foo.com'" - name: Path args: pattern: "'/' + serviceId + '/**'" filters: - name: CircuitBreaker args: name: serviceId - name: RewritePath args: regexp: "'/' + serviceId + '/?(?.*)'" replacement: "'/${remaining}'" ``` -------------------------------- ### Configure Before Predicate with Epoch Milliseconds Source: https://docs.spring.io/spring-cloud-gateway/reference/spring-cloud-gateway-server-webmvc/gateway-request-predicates.html Specify the Before predicate using epoch milliseconds for configuration in application.yml. ```yaml spring: cloud: gateway: mvc: routes: - id: before_route uri: https://example.org predicates: - Before=1484968967789 ``` -------------------------------- ### Configure SetRequestHeader with URI Variable in YAML Source: https://docs.spring.io/spring-cloud-gateway/reference/spring-cloud-gateway-server-webmvc/filters/setrequestheader.html This example shows how to use a URI variable in the SetRequestHeader filter's value within application.yml. ```yaml spring: cloud: gateway: routes: - id: setrequestheader_route uri: https://example.org predicates: - Host: {segment}.myhost.org filters: - SetRequestHeader=X-Request-Red, Blue-{segment} ``` -------------------------------- ### Configure DedupeResponseHeader Filter in application.yml Source: https://docs.spring.io/spring-cloud-gateway/reference/spring-cloud-gateway-server-webmvc/filters/deduperesponseheader.html Configures the DedupeResponseHeader filter in application.yml to deduplicate specified response headers. This example targets 'Access-Control-Allow-Credentials' and 'Access-Control-Allow-Origin'. ```yaml spring: cloud: gateway: server: webmvc: routes: - id: dedupe_response_header_route uri: https://example.org predicates: - Path=/hello filters: - DedupeResponseHeader=Access-Control-Allow-Credentials Access-Control-Allow-Origin ``` -------------------------------- ### Configure Default Filters in application.yml Source: https://docs.spring.io/spring-cloud-gateway/reference/spring-cloud-gateway-server-webflux/gatewayfilter-factories/default-filters.html Use `spring.cloud.gateway.default-filters` to apply filters to all routes. This example adds a response header and a prefix path to all requests. ```yaml spring: cloud: gateway: default-filters: - AddResponseHeader=X-Response-Default-Red, Default-Blue - PrefixPath=/httpbin ``` -------------------------------- ### Configure Weighted Routing with Weight Predicate Factory Source: https://docs.spring.io/spring-cloud-gateway/reference/spring-cloud-gateway-server-webflux/request-predicates-factories.html Shows how to use the Weight route predicate factory in application.yml to distribute traffic between multiple URIs based on assigned weights. This allows for A/B testing or phased rollouts. ```yaml spring: cloud: gateway: routes: - id: weight_high uri: https://weighthigh.org predicates: - Weight=group1, 8 - id: weight_low uri: https://weightlow.org predicates: - Weight=group1, 2 ``` -------------------------------- ### Composing and Invoking Functions Source: https://docs.spring.io/spring-cloud-gateway/reference/spring-cloud-gateway-server-webmvc/java-routes-api.html Invoke a sequence of Spring Cloud Functions by separating their bean names with commas in the URL. This example composes 'concat' and 'uppercase'. ```bash $ curl -d ‘"hello"' -H "Content-Type: application/json" -X POST http://localhost:8080/concat,uppercase ``` -------------------------------- ### Create Multiple Route Definitions Source: https://docs.spring.io/spring-cloud-gateway/reference/spring-cloud-gateway-server-webflux/actuator-api.html Create multiple route definitions in a single request by making a POST request to /gateway/routes. The JSON request body should include the route ID and other fields for each route. Note that if any route creation fails, all route definitions in the request will be discarded. ```shell POST /gateway/routes ``` -------------------------------- ### Configure RequestHeaderSize Filter in Java Source: https://docs.spring.io/spring-cloud-gateway/reference/spring-cloud-gateway-server-webmvc/filters/requestheadersize.html Programmatically configure the RequestHeaderSize filter using Java. This example sets the maximum header size to 1000 Bytes. ```java import static org.springframework.cloud.gateway.server.mvc.filter.BeforeFilterFunctions.uri; import static org.springframework.cloud.gateway.server.mvc.filter.BeforeFilterFunctions.requestHeaderSize; 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 gatewayRouterFunctionsRequestHeaderSize() { return route("requestheadersize_route") .GET("/**", http()) .before(uri("https://example.org")) .before(requestHeaderSize("1000B")) .build(); } } ``` -------------------------------- ### Configure Rate Limiting for a Route Source: https://docs.spring.io/spring-cloud-gateway/reference/spring-cloud-gateway-server-webmvc/filters/ratelimiter.html This snippet shows how to configure a route with rate limiting using Bucket4j. It sets a bucket capacity of 100 tokens per minute and uses the user's principal name as the key for rate limiting. ```java import static org.springframework.cloud.gateway.server.mvc.filter.BeforeFilterFunctions.uri; import static org.springframework.cloud.gateway.server.mvc.filter.Bucket4jFilterFunctions.rateLimit; 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 gatewayRouterFunctionsRateLimited() { return route("rate_limited_route") .GET("/api/**", http()) .before(uri("https://example.org")) .filter(rateLimit(c -> c.setCapacity(100) .setPeriod(Duration.ofMinutes(1)) .setKeyResolver(request -> request.servletRequest().getUserPrincipal().getName()))) .build(); } } ``` -------------------------------- ### Custom Global Post-Filter Source: https://docs.spring.io/spring-cloud-gateway/reference/spring-cloud-gateway-server-webflux/developer-guide.html Implement a global post-filter to modify incoming responses. This example adds a custom response header indicating success or failure. ```java @Bean public GlobalFilter customGlobalPostFilter() { return (exchange, chain) -> chain.filter(exchange) .then(Mono.just(exchange)) .map(serverWebExchange -> { //adds header to response serverWebExchange.getResponse().getHeaders().set("CUSTOM-RESPONSE-HEADER", HttpStatus.OK.equals(serverWebExchange.getResponse().getStatusCode()) ? "It worked": "It did not work"); return serverWebExchange; }) .then(); } ``` -------------------------------- ### Configure SetStatus Filter in application.yml Source: https://docs.spring.io/spring-cloud-gateway/reference/spring-cloud-gateway-server-webmvc/filters/setstatus.html Demonstrates how to configure the SetStatus filter using both string and integer representations of HTTP status codes in application.yml. ```yaml spring: cloud: gateway: server: webmvc: routes: - id: setstatusstring_route uri: https://example.org predicates: - Path=/path1 filters: - SetStatus=UNAUTHORIZED - id: setstatusint_route uri: https://example.org predicates: - Path=/path2 filters: - SetStatus=401 ``` -------------------------------- ### Configure Caffeine AsyncProxyManager for RateLimiter Source: https://docs.spring.io/spring-cloud-gateway/reference/spring-cloud-gateway-server-webmvc/filters/ratelimiter.html Configures an AsyncProxyManager using Caffeine for local in-memory caching. This is useful for testing the RateLimiter Filter. ```java import com.github.benmanes.caffeine.cache.Caffeine; import io.github.bucket4j.caffeine.CaffeineProxyManager; @Configuration class RateLimiterConfiguration { @Bean public AsyncProxyManager caffeineProxyManager() { Caffeine builder = (Caffeine) Caffeine.newBuilder().maximumSize(100); return new CaffeineProxyManager<>(builder, Duration.ofMinutes(1)).asAsync(); } } ``` -------------------------------- ### StripPrefix Filter Configuration in GatewayRouterFunctions Source: https://docs.spring.io/spring-cloud-gateway/reference/spring-cloud-gateway-server-webmvc/filters/stripprefix.html Programmatically configure the StripPrefix filter using GatewayRouterFunctions. This example removes 2 path segments from requests matching /name/**. ```java import static org.springframework.cloud.gateway.server.mvc.filter.BeforeFilterFunctions.stripPrefix; import static org.springframework.cloud.gateway.server.mvc.filter.BeforeFilterFunctions.uri; 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 gatewayRouterFunctionsStripPrefix() { return route("strip_prefix_route") .GET("/name/**", http()) .before(uri("https://example.org")) .before(stripPrefix(2)) .build(); } } ``` -------------------------------- ### Configure DedupeResponseHeader Filter in Java Source: https://docs.spring.io/spring-cloud-gateway/reference/spring-cloud-gateway-server-webmvc/filters/deduperesponseheader.html Configures the DedupeResponseHeader filter programmatically using Java. This example demonstrates how to apply the filter to a route, specifying the headers to deduplicate. ```java import static org.springframework.cloud.gateway.server.mvc.filter.AfterFilterFunctions.dedupeResponseHeader; import static org.springframework.cloud.gateway.server.mvc.filter.BeforeFilterFunctions.uri; import static org.springframework.cloud.gateway.server.mvc.handler.GatewayRouterFunctions.route; import static org.springframework.cloud.gateway.server.mvc.handler.HandlerFunctions.http; import static org.springframework.web.servlet.function.RequestPredicates.path; @Configuration class RouteConfiguration { @Bean public RouterFunction gatewayRouterFunctionsDedupeResponseHeader() { return route("dedupe_response_header_route") .route(path("/hello"), http()) .before(uri("https://example.org")) .after(dedupeResponseHeader("Access-Control-Allow-Credentials Access-Control-Allow-Origin")) .build(); } } ``` -------------------------------- ### Configure Logback for Access Logs Source: https://docs.spring.io/spring-cloud-gateway/reference/spring-cloud-gateway-server-webflux/reactor-netty-access-logs.html This Logback configuration sets up a file appender for access logs and an asynchronous appender to write logs to 'access_log.log'. It configures the 'reactor.netty.http.server.AccessLog' logger to use this appender. ```xml access_log.log %msg%n ``` -------------------------------- ### Invoking a Function with Path Parameter Source: https://docs.spring.io/spring-cloud-gateway/reference/spring-cloud-gateway-server-webmvc/java-routes-api.html Invoke a Spring Cloud Function by using a path parameter for the function's input. This example shows invoking the 'uppercase' function. ```http GET http://localhost:8080/uppercase/hello ``` -------------------------------- ### Configure Retry Filter with Shortcut Syntax Source: https://docs.spring.io/spring-cloud-gateway/reference/spring-cloud-gateway-server-webmvc/filters/retry.html This snippet demonstrates the shortcut syntax for configuring the Retry filter, combining retries, statuses, and methods in a single line. ```yaml - id: retryshortcut_route uri: https://example.org filters: - Retry=3,INTERNAL_SERVER_ERROR,GET ``` -------------------------------- ### Configure RewritePath GatewayFilter in application.yml Source: https://docs.spring.io/spring-cloud-gateway/reference/spring-cloud-gateway-server-webflux/gatewayfilter-factories/rewritepath-factory.html This snippet shows how to configure the RewritePath GatewayFilter in application.yml to rewrite paths starting with /red/ to a new path based on the captured segment. ```yaml spring: cloud: gateway: routes: - id: rewritepath_route uri: https://example.org predicates: - Path=/red/** filters: - RewritePath=/red/?(?.*), /$\{segment} ```