Spring Cloud Alibaba GateWay’s routing assertion factory

Spring Cloud Gateway uses route matching as the most basic function. This function is accomplished through the routing assertion factory. Spring Cloud Gateway contains many built-in routing assertion factories. All these assertions can match different attributes of HTTP requests, and multiple routing assertion factories can be combined based on logic and status.

1. After routing assertion factory

After route assertion accepts one parameter, a datetime (it is a javaZonedDateTime). This assertion will compare the time when the request accesses the Gateway to the date and time specified by this assertion. If the request access time is after the specified parameter, the match is successful and the assertion is true.

1.1 Configuration routing method

spring:
  cloud:
    gateway:
      routes:
      - id: after_route
        uri: https://example.org
        predicates:
        - After=2023-08-12T16:21:07.789-07:00

This assertion only satisfies any request that accesses GateWay after the time of 16:21:07 on August 12, 2023.

Enter the local IP:configuration port number in the browser address bar. If the assertion is met, jump to the https://example.org page. If the assertion requirements are not met, a 404 error code will appear during access.

1.2 API routing method

@Configuration
public class GatewayConfig {

    /**
     * After routing assertion factory - API style
     * @param builder
     * @return
     */
    @Bean
    public RouteLocator afterRouteLocator(RouteLocatorBuilder builder) {

        // Subtract 3 days from the current time and set the system default time zone to the current time zone
        ZonedDateTime dateTime = LocalDateTime.now().minusDays(3).atZone(ZoneId.systemDefault());

        return builder.routes()
                .route("after_route", predicateSpec -> predicateSpec.after(dateTime)
                        .uri("https://example.org"))
                .build();
    }
}

2. Before routing assertion factory

After route assertion accepts one parameter, a datetime (it is a javaZonedDateTime). This assertion will compare the time when the request accesses the Gateway to the date and time specified by this assertion. If the request access time is before the specified parameter, the match is successful and the assertion is true.

2.1 Configuration routing method

spring:
  cloud:
    gateway:
      routes:
      - id: before_route
        uri: https://example.org
        predicates:
        - Before=2025-01-20T16:21:07.789-07:00

This assertion only satisfies any request that accesses GateWay before the time of 16:21:07 on January 20, 2025.

Enter the local IP:configuration port number in the browser address bar. If the assertion is met, jump to the https://example.org page. If the assertion requirements are not met, a 404 error code will appear during access.

2.2 API routing method

@Configuration
public class GatewayConfig {
    /**
     * Before routing assertion factory - API style
     * @param builder
     * @return
     */
    @Bean
    public RouteLocator beforeRouteLocator(RouteLocatorBuilder builder) {

        // Subtract 3 days from the current time and set the system default time zone to the current time zone
        ZonedDateTime dateTime = LocalDateTime.now().minusDays(3).atZone(ZoneId.systemDefault());

        return builder.routes()
                .route("before_route", predicateSpec -> predicateSpec.before(dateTime)
                        .uri("https://example.org"))
                .build();
    }
}

3. Between routing assertion factory

After route assertion accepts two parameters, two date times datetime1 and datetime2 (both of which are javaZonedDateTime objects). This assertion will compare the time when the request accesses the Gateway to the datetime1 and datetime2 specified by this assertion. If the requested access time is before the parameter specified by datetime1 and after the parameter specified by datetime2, the match is successful and the assertion is true.

3.1 Configuration routing method

spring:
  cloud:
    gateway:
      routes:
      - id: between_route
        uri: https://example.org
        predicates:
        - Between=2018-09-20T16:21:07.789-07:00, 2025-01-21T16:21:07.789-07:00

This assertion only satisfies any request that accesses GateWay after 16:21:07 on September 20, 2018, and before 16:21:07 on January 20, 2025.

Enter the local IP:configuration port number in the browser address bar. If the assertion is met, jump to the https://example.org page. If the assertion requirements are not met, a 404 error code will appear during access.

3.2 API routing method

@Configuration
public class GatewayConfig {
    /**
     * Between routing assertion factory - API style
     * @param builder
     * @return
     */
    @Bean
    public RouteLocator betweenRouteLocator(RouteLocatorBuilder builder) {

        // Subtract 3 days from the current time and set the system default time zone to the current time zone
        ZonedDateTime dateTimeBegin = LocalDateTime.now().minusDays(3).atZone(ZoneId.systemDefault());
        //Add 5 days to the current time and set the system default time zone to the current time
        ZonedDateTime dateTimeAfter = LocalDateTime.now().plusDays(5).atZone(ZoneId.systemDefault());

        return builder.routes()
                .route("between_route", predicateSpec -> predicateSpec.between(dateTimeBegin, dateTimeAfter)
                        .uri("https://example.org"))
                .build();
    }
}

4. Cookie routing assertion factory

Cookie routing assertion accepts two parameters, namely Cookie key and value (value is a Java regular expression). This assertion will be compared with the cookie carried in the request to access the Gateway. If the requested cookie carries the specified key and value, the match is successful and the assertion is true.

4.1 Configuration routing method

spring:
  cloud:
    gateway:
      routes:
      - id: cookie_route
        uri: https://example.org
        predicates:
        - Cookie=chocolate, ch.p

use
Postman
Carry out a test and add the assertion that satisfies the assertion in the request header.
Cookies
, you can successfully access the page. But if no cookies are set
or set
Cookie key and value do not meet the specifications
assertion is inaccessible.

4.2 API routing method

@Configuration
public class GatewayConfig {
    /**
     * Cookie routing assertion factory - API style
     * @param builder
     * @return
     */
    @Bean
    public RouteLocator cookieRouteLocator(RouteLocatorBuilder builder) {

        return builder.routes()
                .route("cookie_route", predicateSpec -> predicateSpec.cookie("city", "siping")
                        .uri("https://example.org"))
                .build();
    }
}

5. Header routing assertion factory

Header routing assertion accepts two parameters, namely the key and value of the request header Header (value is a Java regular expression). This assertion will be compared with the Header carried in the request to access the Gateway. If the requested Header carries the specified key and value, the match is successful and the assertion is true.

5.1 Configuration routing method

spring:
  cloud:
    gateway:
      routes:
      - id: header_route
        uri: https://example.org
        predicates:
        - Header=X-Request-Id, \d +

Use Postman to test and add a header that satisfies the assertion in the request header, and you can successfully access the page. However, if the Header is not set or the key and value of the set Header do not satisfy the specified assertion, it cannot be accessed.

5.2 API routing method

@Configuration
public class GatewayConfig {
    /**
     * Header routing assertion factory - API style
     * @param builder
     * @return
     */
    @Bean
    public RouteLocator headerRouteLocator(RouteLocatorBuilder builder) {

        return builder.routes()
                .route("header_route", predicateSpec -> predicateSpec.header("X-Request-Id", "\d + ")
                        .and()
                        .header("Color", "re. + ")
                        .uri("https://example.org"))
                .build();
    }
}

6. Host routing assertion factory

Host routing assertion accepts one parameter, which is a list of hostname patterns (Host attribute in the request header). When the request carries the specified Host attribute value, the match is successful and the assertion is true. ?

6.1 Configuration routing method

spring:
  cloud:
    gateway:
      routes:
      - id: host_route
        uri: https://example.org
        predicates:
        - Host=**.somehost.org, **.anotherhost.org

6.2 API routing method

@Configuration
public class GatewayConfig {
    /**
     * Host routing assertion factory - API style
     * @param builder
     * @return
     */
    @Bean
    public RouteLocator hostRouteLocator(RouteLocatorBuilder builder) {
        return builder.routes()
                .route("host_route", predicateSpec -> predicateSpec
                    .host(**.somehost.org, **.anotherhost.org)
                    .uri("https://example.org"))
                .build();
    }
}

7. Method routing assertion factory

Method routing assertion accepts a parameter, which can be one parameter or multiple parameters. This parameter specifies the request method (POST, GET, PUT, DELETE). When the specified request method is used in the request, the match is successful and the assertion is true.

7.1 Configuration routing method

spring:
  cloud:
    gateway:
      routes:
      - id: method_route
        uri: https://example.org
        predicates:
        - Method=GET, POST

This assertion only satisfies any request to GateWay whose request method is GET or POST.

7.2 API routing method

@Configuration
public class GatewayConfig {
    
    /**
     * Method routing assertion factory - API style
     * @param builder
     * @return
     */
    @Bean
    public RouteLocator methodRouteLocator(RouteLocatorBuilder builder) {

        return builder.routes()
                .route("method_route", predicateSpec -> predicateSpec
                    .method("GET", "POST")
                    .uri("https://example.org"))
                .build();
    }
}

8. Path routing assertion factory

Method routing assertion accepts two parameters. The first parameter is the Spring PathMatcher pattern list, that is, URI; the second parameter is an optional flag named matchTrailingFlash (default is true). When the request path contains the specified URI, the match is successful and the assertion is true. And the matching URI will be spliced to the back of the target URI to be redirected to form a unified URI.

8.1 Configuration routing method

spring:
  cloud:
    gateway:
      routes:
      - id: path_route
        uri: https://example.org
        predicates:
        - Path=/red/{segment},/blue/{segment}

8.2 API routing method

@Configuration
public class GatewayConfig {
    /**
     * Between routing assertion factory - API style
     * @param builder
     * @return
     */
    @Bean
    public RouteLocator betweenRouteLocator(RouteLocatorBuilder builder) {

        // Subtract 3 days from the current time and set the system default time zone to the current time zone
        ZonedDateTime dateTimeBegin = LocalDateTime.now().minusDays(3).atZone(ZoneId.systemDefault());
        //Add 5 days to the current time and set the system default time zone to the current time
        ZonedDateTime dateTimeAfter = LocalDateTime.now().plusDays(5).atZone(ZoneId.systemDefault());

        return builder.routes()
                .route("between_route", predicateSpec -> predicateSpec.between(dateTimeBegin, dateTimeAfter)
                        .uri("https://example.org"))
                .build();
    }
}https://example.org

9. Query routing assertion factory

The Query route assertion factory accepts two parameters, a required request parameter param and an optional regexp (which is a Java regular expression). When the request contains the specified parameter name, or name-value pair, the match is successful and the assertion is True.

9.1 Configuration routing method

spring:
  cloud:
    gateway:
      routes:
      - id: query_route
        uri: https://example.org
        predicates:
        -Query=green
spring:
  cloud:
    gateway:
      routes:
      - id: query_route
        uri: https://example.org
        predicates:
        - Query=red, gree.

9.2 API routing method

@Configuration
public class GatewayConfig {
    /**
     * Query routing assertion factory - API style
     * @param builder
     * @return
     */
    @Bean
    public RouteLocator queryRouteLocator(RouteLocatorBuilder builder) {

        return builder.routes()
                .route("query_route", predicateSpec -> predicateSpec
                        .query("color", "gr. + ")
                        .and()
                        .query("size")
                        .uri("https://example.org"))
                .build();
    }
}

10. RemoteAddr routing assertion factory

RemoteAddr routing assertion factory is used to determine whether the client IP address submitting the request is in the IP range or IP list specified in the assertion. If the requested client IP is in the specified IP range or IP list, the match is successful and the assertion is True. For example, 192.168.0.1/16 (where 192.168.0.1 is the IP address and 16 is the subnet mask).

10.1 Configuration routing method

spring:
  cloud:
    gateway:
      routes:
      - id: remoteaddr_route
        uri: https://example.org
        predicates:
        - RemoteAddr=192.168.3.1/24

This assertion only satisfies any request that accesses the GateWay host IP belonging to the 192.168.3 network segment.

10.2 API routing method

@Configuration
public class GatewayConfig {
    /**
     * RemoteAddr routing assertion factory - API style
     * @param builder
     * @return
     */
    @Bean
    public RouteLocator remoteAddrRouteLocator(RouteLocatorBuilder builder) {
        return builder.routes()
                .route("remoteAddr_route", predicateSpec -> predicateSpec
                    .remoteAddr("192.168.3.1/24")
                    .uri("https://example.org"))
                .build();
    }
}

11. Weight routing assertion factory

The Weight routing assertion factory accepts two parameters, one is the group; the other is the weight Weight (an int). This assertion is used to implement load balancing with specified weights for different URIs in the same group. For multiple URI addresses in the same group, the router will forward the requests to the corresponding URIs in proportion according to the set weights.

11.1 Configuration routing method

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

11.2 API routing method

@Configuration
public class GatewayConfig {
    /**
     * Weight routing assertion factory - API style
     * @param builder
     * @return
     */
    @Bean
    public RouteLocator weightRouteLocator(RouteLocatorBuilder builder) {

        return builder.routes()
                .route("weight_high", predicateSpec -> predicateSpec
                    .weight(group1, 8)
                    .uri("https://weighthigh.org"))
                .route("weight_low", predicateSpec -> predicateSpec
                    .weight(group2, 2)
                    .uri("https://weightlow.org"))
                .build();
    }
}

12. XForwarded Remote Addr routing assertion factory

The XForwarded Remote Addr routing assertion factory accepts one parameter, which is an IP address, such as 192.168.0.1/16 (where 192.168.0.1 is the IP address and 16 is the subnet mask). As long as the IP with X-Forwarded-For appended to the current request header appears in the IP list specified by the route, the match is successful and the assertion is true.

12.1 Configuration routing method

spring:
  cloud:
    gateway:
      routes:
      - id: xforwarded_remoteaddr_route
        uri: https://example.org
        predicates:
        - XForwardedRemoteAddr=192.168.1.1/24, 192.168.60.10

12.2 API routing method

@Configuration
public class GatewayConfig {
    /**
     * XForwardedRemoteAddr routing assertion factory - API style
     * @param builder
     * @return
     */
    @Bean
    public RouteLocator xForwardedRemoteAddrRouteLocator(RouteLocatorBuilder builder) {

        return builder.routes()
                .route("xForwardedRemoteAddr_route", predicateSpec -> predicateSpec
                    .xForwardedRemoteAddr("192.168.1.1/24", "192.168.60.10")
                    .uri("https://example.org"))
                .build();
    }
}