Dynamic configuration of Spring Cloud Gateway Routing

Keywords: Programming Spring Java JSON Attribute

Address of original English document: click here

8. Configure the route according to the configuration document

The configuration of Spring Cloud Gateway is controlled by a series of "RouteDefinitionLocator" interfaces, which are as follows:

public interface RouteDefinitionLocator {
	Flux<RouteDefinition> getRouteDefinitions();
}

By default, through the @ ConfigurationProperties mechanism of Spring Boot, Spring Cloud Gateway uses PropertiesRouteDefinitionLocator to load the configuration information of routes from the configuration file. In the previous routing configuration, a quick configuration method was used, and specific parameter names can also be specified. For example, the following two configuration methods have the same effect:

spring:
  cloud:
    gateway:
      routes:
      - id: setstatus_route
        uri: http://example.org
        filters:
        - name: SetStatus
          args:
            status: 401
      - id: setstatusshortcut_route
        uri: http://example.org
        filters:
        - SetStatus=401

In some application scenarios of gateways, you can use attribute configuration, but in some production environments, some routing configuration information may come from other places, such as databases. In the future version of Spring Cloud Gateway, some database based RouteDefinitionLocator implementation classes will be added, such as redis and mongodb.

8.1 Fluent Java Routes API (use Java route api code to add route configuration)

Some fluent APIs defined in RouteLocatorBuilder can be used to configure related routing information in Java code, as shown in the following code:

// static imports from GatewayFilters and RoutePredicates
@Bean
    public RouteLocator customRouteLocator(RouteLocatorBuilder builder, AddRequestHeaderGatewayFilterFactory throttle) {
        NameValueConfig requestHeader = new NameValueConfig();
        requestHeader.setName("routes-a");
        requestHeader.setValue("yes");
        return builder.routes()
                .route(r -> r.host("localhost:8080").and().path("/routes-api/a/**")
                    .filters(f ->{
                            f.addResponseHeader("X-TestHeader", "foobar");
                            return f.redirect(HttpStatus.MOVED_PERMANENTLY.value(), "http://www.xinyues.com");
                            })
                    .uri("http://localhost:8080").id("custom-1")
                )
                .route(r -> r.path("/routes-api/b/**")
                    .filters(f ->
                            f.addResponseHeader("X-AnotherHeader", "baz"))
                    .uri("http://localhost:8080").id("custom-2")
                )
                .route(r -> r.order(0)
                    .host("localhost:8080").and().path("/routes-api/c/**")
                    .filters(f -> f.filter(throttle.apply(requestHeader)))
                    .uri("http://localhost:8080").id("custom-3")
                )
                .build();
    }

This code is implemented by myself referring to the original document. The throttle gateway filter factory above the original document cannot be found. Here I added a custom routes Id, which can be viewed from the source code: https://gitee.com/wgslucky/SpringCloud , start the source project, and enter: Http: / / localhost: 8080 / Actor / gateway / routes, you can see all the routing information loaded by the gateway, and you can see the routing information with the routing id of custom-x in the code, indicating that the routing configuration added in Java and the routing configuration added in the configuration file have been loaded to. It's more intuitive if the browser has the Json plug-in installed. This is a routing configuration Json array. According to the routing configuration in the above code, enter: http: / / localhost: 8080 / routes API / A / test in the browser. You can see that the successful jump to the target website indicates that the routing configuration is successful. In this form, you can also add some custom Predicate judgments. The Predicates defined in route definition locator can use logical and. With Fluent Java Api, you can use and(),or(), and gate () to manipulate the Predicate class. For example, the first route in the above code uses and() to add two Predicates.

8.2 DiscoveryClient Route Definition Locator uses service discovery client to define route information

Spring Cloud Gateway can use the service discovery client interface DiscoveryClient to obtain service registration information from the service attention center, and then configure the corresponding routes. Note that you need to add the following configuration in the configuration to enable this function:

spring.cloud.gateway.discovery.locator.enabled=true

Then make sure that the service discovery client dependency of the implementation class of DiscoveryClient has been introduced, such as Eureka,Consul or Zookeeper.

8.2.1 Configuring Predicates and Filters For DiscoveryClient Routes

By default, only one default Predicate and Filter is included in the route information automatically configured by the service discovery client discovery client. The default Predicate is a Path Predicate. The mode is / serviceId / * *. serviceId is the service ID obtained from the service discovery client. The default Filter is a path rewriting Filter. Its regular expression is: / serviceId / (? < remaining >. *). Its function is to remove the serviceId from the request path and change it to / (? < remaining >. *). If you want to add a custom Predicate and filters, you can configure them as follows: spring.cloud.gateway.discovery.locator.predictions [x] and spring.cloud.gateway.discovery.location Or. Filters [y], when this configuration mode is used, the original default Predicate and Filter will not be retained. If you need the original configuration, you need to add it to the configuration manually, as shown below: application.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: Hystrix
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 + '/(?<remaining>.*)'"
spring.cloud.gateway.discovery.locator.filters[1].args[replacement]: "'/${remaining}'"

application.yml

spring: 
  cloud: 
    gateway: 
      discovery:
        locator:
          enabled: true
          predicates:
          - name: Path
            args:
              pattern: "'/'+serviceId+'/test'"
          filters: 
          - name: RedirectTo
            args:
              status: 301
              url: "'http://www.xinyues.com'"

Note that in these configurations, the values of all configurations will be parsed by Spel, so if it is a string, quotation marks are needed. For example, in application.yml, if the configuration is as follows: url: http://www.xinyues.com, an error will be reported. For details, see: https://www.cnblogs.com/wgslucky/p/11743740.html

application.yml: this configuration keeps the original default Predicate and Filter.

spring: 
  cloud: 
    gateway: 
      discovery:
        locator:
          enabled: true
          predicates:
          - name: Path
            args:
              pattern: "'/'+serviceId+'/**'"
          filters: 
          - name: AddRequestHeader
            args: 
             name: "'foo'"
             value: "'bar'"
          - name: RewritePath
            args:
              regexp: "'/' + serviceId + '/(?<remaining>.*)'"
              replacement: "'/${remaining}'"

You can see that all strings must be in single quotes.

Mobile phone stand lazy stand desktop ipad tablet computer creative portable stand multi-functional live broadcasting shaking photo landing bedside live broadcasting car folding support

8.2.2 source code implementation

Download the source code here: https://gitee.com/wgslucky/SpringCloud

  1. Modify application.yml to activate the discovery client configuration file
spring:
  profiles:
    active:
    - discoveryclient
  1. Launch the spring cloud Gateway project
  2. Launch the spring cloud app a project

Then enter: Http: / / localhost: 8080 / Actor / gateway / routes, you can see that the route information to the spring-cloud-app-a service has been added successfully, as shown below: You can see that there is a default filter and predicate. It can be seen that the routing information configured in the configuration file and the routing configuration information added in the java code are all loaded into the gateway, indicating that the three ways to configure the routing information can be used together.

Posted by tommyrulez on Sat, 26 Oct 2019 10:40:07 -0700