Gateway configuration introduction

Posted by apollo on Tue, 04 Jan 2022 20:52:28 +0100

Route predicate factories configuration

Official documents: https://docs.spring.io/spring-cloud-gateway/docs/current/reference/html/#gateway-request-predicates-factories

The spring cloud gateway includes many built-in assertion factories, all of which match different attributes of HTTP requests. The details are as follows:
1. Assertion factory based on Datetime type
This type of assertion is judged according to time, mainly in three ways:
1> AfterRoutePredicateFactory: receives a date parameter to judge whether the request date is later than the specified date
2> BeforeRoutePredicateFactory: receives a date parameter to judge whether the request date is earlier than the specified date
3> BetweenRoutePredicateFactory: receives two date parameters to judge whether the request date is within the specified time period

- After=2017-01-20T17:42:47.789-07:00[America/Denver]
- Before=2017-01-20T17:42:47.789-07:00[America/Denver]
- Between=2017-01-20T17:42:47.789-07:00[America/Denver], 2017-01-21T17:42:47.789-07:00[America/Denver]

2. Assertion factory based on remote address
Remoteaddroutepredicatefactory: receive an IP address field and judge whether the request host address is in the address field

- RemoteAddr=192.168.1.1/24

3. Cookie based assertion factory
Cookie route predicatefactory: receives two parameters, the cookie name and a regular expression. Determine whether the request cookie has the given name and the value matches the regular expression.

- Cookie=chocolate, ch.p

4. Header based assertion factory
HeaderRoutePredicateFactory: receives two parameters, the title name and the regular expression. Judge whether the request Header has the given name and the regular expression matches.

- Header=X-Request-Id, \d+

5. Host based assertion factory
HostRoutePredicateFactory: receives a parameter, hostname mode. Judge whether the requested Host meets the matching rules.

- Host=**.somehost.org,**.anotherhost.org

6. Assertion factory based on Method request Method
MethodRoutePredicateFactory: receives a parameter to judge whether the request type matches the specified type.

- Method=GET,POST

7. Assertion factory based on Path request Path
PathRoutePredicateFactory: receives a parameter to judge whether the URL part of the request meets the path rules.

- Path=/red/{segment},/blue/{segment}

8. Assertion factory based on Query request parameters
QueryRoutePredicateFactory: receives two parameters, request param and regular expression, and judges whether the request parameter has the given name and the value matches the regular expression.

- Query=green
- Query=red, gree.

9. Assertion factory based on routing weight
WeightRoutePredicateFactory: receive a [group name, weight], and then forward the routes in the same group according to the weight.

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

Custom route assertion factory

The custom route assertion factory needs to inherit the AbstractRoutePredicateFactory class and override the logic of the apply method. In the apply method, you can use exchange Getrequest () gets the ServerHttpRequest object, so you can get the request parameters, request method, request header and other information.
Note: the name needs to end with RoutePredicateFactory
1> Must be a spring component bean
2> Class must end with RoutePredicateFactory
3> You must inherit AbstractRoutePredicateFactory
4> You must declare a static inner class declaration property to receive information about the corresponding assertion in the configuration file
5> It needs to be bound in combination with shortcutFieldOrder
6> Make a logical judgment through apply. true means that the matching is successful and false means that the matching fails

1. Custom route assertion factory

@Slf4j
@Component
public class CheckRoutePredicateFactory extends AbstractRoutePredicateFactory<CheckRoutePredicateFactory.Config> {

    public CheckRoutePredicateFactory() {
        super(CheckRoutePredicateFactory.Config.class);
    }

    public List<String> shortcutFieldOrder() {
        return Arrays.asList("name");
    }

    public Predicate<ServerWebExchange> apply(CheckRoutePredicateFactory.Config config) {
        return new GatewayPredicate() {

            public boolean test(ServerWebExchange exchange) {
                if(config.getName().equals("mu")){
                    return true;
                }
                return false;
            }

        };
    }

    /**
     * Information used to receive profile interrupts
     */
    @Validated
    public static class Config {
        private String name;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }
}

2.application.yml configuration

server:
  port: 8088
# Application name (nacos will take this name as the service name)
spring:
  application:
    name: api-gateway
  cloud:
    # gateway configuration
    gateway:
      # Routing rules
      routes:
        - id: order_route  # Unique identification of the route to order
          uri: lb://Order service # address to be forwarded lb: use the local load balancing policy in nacos
          # Assertion rules are used to match routing rules
          predicates:
            - Path=/order/**
            - Check=mu
    # Configuring nacos
    nacos:
      server-addr: 127.0.0.1:8848
      discovery:
        username: nacos
        password: nacos
        namespace: public

3. Test

Giteway filter factories configuration

There are many built-in filter factories in the Gateway. Through some filter factories, we can carry out some business logic processors, such as adding and removing response headers, adding and removing parameters, etc.

Filter factoryeffectparameter
AddRequestHeaderAdd Header for original requestName and value of Header
AddRequestParameterAdd request parameters to the original requestParameter name and value
DedupeResponseHeaderEliminate duplicate values in response headersHeader name and de duplication policy that need to be de duplicated
HystrixIntroduce circuit breaker protection of Hystrix for routingThe name of the HystrixCommand
FallbackHeadersAdd specific exception information to the request header of fallbackUnThe name of the Header
PrefixPathPrefix the original request pathFront end path
PreserveHostHeaderAdd a property of preserveHostHeader=true to the request, and the routing filter will check this property to determine whether to send the original Hostnothing
RequestRateLimiterIt is used to limit the current of requests. The current limiting algorithm is token bucketkeyResolver,rateLimiter,statusCode,denyEmptyKey,emptyKeyStatus
RedirectToRedirects the original request to the specified URLhttp status code and redirected url
RemoveHopByHopHeadersFilterDelete a series of headers specified by the IETF organization for the original requestIt is enabled by default, and you can specify which headers to delete only through configuration
RemoveRequestHeaderDelete a Header for the original requestHeader name
RemoveResponseHeaderDelete a Header for the original responseHeader name
RewritePathRewrite the original request pathThe regular expression of the original path and the rewritten path
RewriteResponseHeaderOverride a Header in the original responseRegular expression of Header name and value, overridden value
SaveSessionForce the WebSession:save operation before forwarding the requestnothing
secureHeadersAdd a series of security response headers to the original responseNone. Modifying the values of these security response headers is supported
SetPathModify the original request pathModified path
SetResponseHeaderModify the value of a Header in the original responseHeader name, modified value
SetStatusModify the status code of the original responseHTTP status code, which can be a number or a string
StripPrefixThe path used to truncate the original requestUse a number to indicate the number of paths to truncate
RetryRetry for different responsesretries,statuses,methods,series
RequestSizeSet the size of the maximum request packet allowed to be received. If the request packet size exceeds the set value, 413Payload Too Large is returnedThe required packet size is in bytes, and the default value is 5M
ModifyRequestBodyModify the original request body content before forwarding the requestModified request body content
ModifyResponseBodyModify the contents of the original response bodyModified response body content

1. Add request header

server:
  port: 8088
# Application name (nacos will take this name as the service name)
spring:
  application:
    name: api-gateway
  cloud:
    # gateway configuration
    gateway:
      # Routing rules
      routes:
        - id: order_route  # Unique identification of the route to order
          uri: lb://Order service # address to be forwarded lb: use the local load balancing policy in nacos
          # Assertion rules are used to match routing rules
          predicates:
            - Path=/order/**
          filters:
            - AddRequestHeader=X-Request-color, red  # Add request header
    # Configuring nacos
    nacos:
      server-addr: 127.0.0.1:8848
      discovery:
        username: nacos
        password: nacos
        namespace: public

test

@RestController
@RequestMapping("/order")
@Slf4j
public class OrderController {

    @Autowired
    private RestTemplate restTemplate;

    @RequestMapping("/header")
    public String header(@RequestHeader("X-Request-color") String color){
        String result = restTemplate.getForObject("http://stock-service/stock/reduct", String.class);
        log.info("Order successfully!");
        return "Hello World !" + result + color;
    }

}

2. Uniformly add prefixes to the matched routes

server:
  port: 8088
# Application name (nacos will take this name as the service name)
spring:
  application:
    name: api-gateway
  cloud:
    # gateway configuration
    gateway:
      # Routing rules
      routes:
        - id: order_route  # Unique identification of the route to order
          uri: lb://Order service # address to be forwarded lb: use the local load balancing policy in nacos
          # Assertion rules are used to match routing rules
          predicates:
            - Path=/order/**
          filters:
            - AddRequestHeader=X-Request-color, red  # Add request header
            - PrefixPath=/mu   # The context path needs to be configured for the micro service corresponding to the prefix
    # Configuring nacos
    nacos:
      server-addr: 127.0.0.1:8848
      discovery:
        username: nacos
        password: nacos
        namespace: public

Configuration is required in order Nacos

server:
  port: 8020
  servlet:
    context-path: /mu

Test:

3. Redirect operation

server:
  port: 8088
# Application name (nacos will take this name as the service name)
spring:
  application:
    name: api-gateway
  cloud:
    # gateway configuration
    gateway:
      # Routing rules
      routes:
        - id: order_route  # Unique identification of the route to order
          uri: lb://Order service # address to be forwarded lb: use the local load balancing policy in nacos
          # Assertion rules are used to match routing rules
          predicates:
            - Path=/order/**
          filters:
            - AddRequestHeader=X-Request-color, red  # Add request header
            - PrefixPath=/mu   # The context path needs to be configured for the micro service corresponding to the prefix
            - RedirectTo=302, https://www.baidu.com / # add redirect
    # Configuring nacos
    nacos:
      server-addr: 127.0.0.1:8848
      discovery:
        username: nacos
        password: nacos
        namespace: public

Test:

4. Custom filter factory
Inherits AbstractNameValueGatewayFilterFactory, and our custom name must end with GatewayFilterFactory and be handed over to spring management.

@Component
public class CheckAuthGatewayFilterFactory extends AbstractGatewayFilterFactory<CheckAuthGatewayFilterFactory.Config> {

    public CheckAuthGatewayFilterFactory() {
        super(CheckAuthGatewayFilterFactory.Config.class);
    }

    public List<String> shortcutFieldOrder() {
        return Arrays.asList("value");
    }

    @Override
    public GatewayFilter apply(Config config) {
        return new GatewayFilter() {
            @Override
            public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
                String name = exchange.getRequest().getQueryParams().getFirst("name");
                if(StringUtils.isNotBlank(name)){
                    if(config.getValue().equals(name)){
                        return chain.filter(exchange);
                    }else{
                        //Return to 404 end
                        exchange.getResponse().setStatusCode(HttpStatus.NOT_FOUND);
                        return exchange.getResponse().setComplete();
                    }
                }
                //Normal request
                return chain.filter(exchange);
            }
        };
    }


    public static class Config {
        private String value;

        public String getValue() {
            return value;
        }

        public void setValue(String value) {
            this.value = value;
        }
    }
}

Configure custom filter factory

server:
  port: 8088
# Application name (nacos will take this name as the service name)
spring:
  application:
    name: api-gateway
  cloud:
    # gateway configuration
    gateway:
      # Routing rules
      routes:
        - id: order_route  # Unique identification of the route to order
          uri: lb://Order service # address to be forwarded lb: use the local load balancing policy in nacos
          # Assertion rules are used to match routing rules
          predicates:
            - Path=/order/**
          filters:
            - CheckAuth=mry
            - PrefixPath=/mu   # The context path needs to be configured for the micro service corresponding to the prefix
    # Configuring nacos
    nacos:
      server-addr: 127.0.0.1:8848
      discovery:
        username: nacos
        password: nacos
        namespace: public

Test:


Gateway global filter


Difference between local filter and global filter:
Local: for a route, it needs to be configured in the route
Global: for all routing requests, once defined, they will be put into use

GlobalFilter interface has the same interface definition as GatewayFilter, but GlobalFilter will act on all routes.

1.LoadBalancerClientFilter
LoadBalancerClientFilter will view the property serverwebexchangeutils. Of exchange GATEWAY_ REQUEST_ URL_ The value of attr (a URL). If the scheme of the value is lb, such as lb://myservice, it will use the LoadBalancerClient of Spring Cloud to parse myservice into the actual host and port, and replace serverwebexchangeutils GATEWAY_ REQUEST_ URL_ Contents of attr.
In fact, it is used to integrate the Ribbon of load balancing

@Slf4j
@Component
public class LogFilter implements GlobalFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info(exchange.getRequest().getPath().value());
        return chain.filter(exchange);
    }

}

Test:

Reactor Netty access log

To start Reactor Netty access log, set - dreamer netty. http. server. accessLogEnabled=true
It must be a Java system property, not a Spring Boot property.

You can configure the logging system to have separate access log files. The following example creates a Logback configuration:

Gateway cross domain configuration (CORS Configuration)

By yml configuration
https://docs.spring.io/spring-cloud-gateway/docs/current/reference/html/#cors-configuration

spring:
  cloud:
    gateway:
      globalcors:
        cors-configurations:
          '[/**]':   # Resources that allow cross domain access
            allowedOrigins: "https://docs.spring.io "# cross domain allowed sources
            allowedMethods:
            - GET
            - POST

Through java configuration

@Configuration
public class CorsConfig{
	@Bean
	public CorsWebFilter corsFilter(){
		CorsConfiguration config = new CorsConfiguration();
		config.addAllowedMethod("*");
		config.addAllowedOrigin("*");
		config.addAllowedHeader("*");
		
		UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
		source.registerCorsConfiguration("/**", config);
		return new CorsWebFilter(source);
	}
}

Topics: Java Spring Cloud gateway