Spring Cloud(2020.0.3) | from entry to soil - 22. Gateway filter factory

1, Gateway filter chain

We saw a picture when we first introduced Gateway. Now let's take a look.

 

In the last two blogs, we talked about Gateway Handler Mapping. Next, we want to talk about the whole Filter chain.

!!! Here, the Filter in the Gateway is not the same as the Filter in our Servlet

2, Gateway filter

There are many built-in filters in the Gateway. There are two types of filters: Gateway Filter and GlobalFilter.

GatewayFilter only works on a single route or routes of the same packet, while GlobalFilter works on all routes.

In addition, Filter can be divided into pre route and Post route.

Pre Routing: before the request is forwarded to a specific service, we can perform operations such as authentication, path rewriting and flow restriction in the pre routing;

Post route: it is the route that returns from the gateway to the front end after the request is completed. We can modify the Http status code in the post route or add something in the Response;

There are many types of filters. See the official website for details: Spring Cloud Gateway  , We won't finish talking about all kinds of filters. We can only talk about a few representative ones. Let's see the rest of the filters by ourselves~~~

3, AddRequestHeader   GatewayFilter

AddRequestHeader   Gateway filter: add a request header filter, which is one of the pre filters.

Function: you can add a request header parameter to the request after the request comes in.

Parameters: name, value.

gateway application.yml

spring:
  cloud:
    gateway:
      routes:
      - id: path_route
        uri: http://localhost:3000/
        predicates:
        - Path=/normal/**
        filters:
        - AddRequestHeader=X-Request-red, blue

Here, name is X-Request-red and value is blue. After configuration, we can get this value in our business code.

Start the service and test it.

But! This value will not change. Whenever we get it, it will be blue. Even if we add other value values to the request, it will be overwritten and set to blue.

4, AddResponseHeader   GatewayFilter

AddResponseHeader   Gateway filter: add a response header filter, which is one of the post filters.

Function: after the request is completed, when it is returned to the front end or the calling end, set the response header to return.

Parameters: name, value.

gateway application.yml

spring:
  cloud:
    gateway:
      routes:
      - id: path_route
        uri: http://localhost:3000/
        predicates:
        - Path=/normal/**
        filters:
        - AddResponseHeader=X-Response-Red, Blue

Restart the service and request again.

After the request is successful, you can see that there is an additional X-Response-Red data in the response header.

5, RewritePath   GatewayFilter

RewritePath   Gateway filter: path rewriting filter, which is one of the prefilters.

Function: after the request comes, rewrite the path according to the rules (to protect the system), and finally make the request according to the rewritten path.

Parameters: path before rewriting, path after rewriting

gateway application.yml

spring:
  cloud:
    gateway:
      routes:
      - id: path_route
        uri: http://localhost:3000/
        predicates:
        - Path=/red/**
        filters:
        - RewritePath=/red/?(?<segment>.*), /normal/$\{segment}

Here, we request red, and then when we get the request, we replace red with normal.

6, Custom local filter (I) not recommended

In addition to using the filters provided by Gateway, we can also customize them.

Local filters like the above implement an interface of Gateway: Gateway filter.

You can look through it yourself. When we define our own custom filters, we also need to implement this interface.

1. First, let's define a Filter. The class name is MyGatewayFilter (this name can be chosen at will)

public class MyGatewayFilter implements GatewayFilter, Ordered {

	public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
		System.out.println("Customization performed Gateway filter");
		return chain.filter(exchange);
	}

	public int getOrder() {
		return 0;
	}

}

Here we implement the GatewayFilter and Ordered interfaces.

In the filter method, we output a sentence and execute the custom Gateway filter. We can get request and response through exchange.

The getOrder method is to sort the Gateway.

2. Next, we apply this filter to the request. Similarly, a configuration class is defined here.

@Configuration
public class MyGatewayFilterConfig {

	@Bean 
	public RouteLocator routeLocator(RouteLocatorBuilder builder){
		return builder.routes().route(
				r -> r.path("/normal/**")
					.filters(f -> f.filter(new MyGatewayFilter()))
					.uri("http://localhost:3000/")
				).build();
	}
}

Here, we don't need to define id.

Next, we delete all the gateway configurations in yml, leaving only one port configuration.

server:
  port: 7200
  servlet:
    context-path: /
  tomcat:
    uri-encoding: UTF-8

Restart the service to test~~~~

As you can see, the request can proceed and the Gateway filter is executed.

7, Custom local filter (II) recommendation

In addition to the code configuration above, we can also use yml configuration to introduce our custom filters.

1. First define a   SomethingGatewayFilterFactory (the name is fixed!!! Must be xxx + GatewayFilterFactory). This factory class needs to inherit   AbstractGatewayFilterFactory.

@Component
public class SomethingGatewayFilterFactory extends AbstractGatewayFilterFactory<SomethingGatewayFilterFactory.Config> {
	
	public SomethingGatewayFilterFactory() {
        super(Config.class);
    }
	

	@Override
	public GatewayFilter apply(Config config) {
		return new MyGatewayFilter();
	}
	
	public static class Config {
		
	}

}

Some configurations can be written in the Config class. For this, please refer to other gatewayfilters.

2. Previous definitions   The RouteLocator code is commented out.

//	@Bean 
//	public RouteLocator routeLocator(RouteLocatorBuilder builder){
//		return builder.routes().route(
//				r -> r.path("/normal/**")
//					.filters(f -> f.filter(new MyGatewayFilter()))
//					.uri("http://localhost:3000/")
//				).build();
//	}

3. Add configuration in yml

spring:
  cloud:
    gateway:
      routes:
      - id: path_route
        uri: http://localhost:3000/
        predicates:
        - Path=/normal/**
        filters:
        - Something

  Here, choose a relatively simple Path routing rule; filters use the name we just defined, which is xxx as we said above+   xxx in GatewayFilterFactory.

Start the service and let's test it.

8, GlobalFilter   Gateway

The Gateway global filter does not need to be configured in yml (because it functions in all requests). We can use it to do a lot of unified business processing (load, log, monitoring, etc.).

The global filter and the above Gateway filter together form the whole Gateway filter chain (customized ones do not count). The execution Order of the global filter chain is determined according to the configuration. You can specify the number size through the annotation: @ Order. The smaller the number, the higher the priority.

9, Custom global filter

Defining a global filter does not need to be so troublesome. We only need to define the filter we need. Here, we can directly use the code.

@Order(0)
@Component
public class MyGlobalFilter implements GlobalFilter {

	@Override
	public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
		System.out.println("Global filter~~");
		return chain.filter(exchange);
	}

}

Instead of implementing the Order interface, annotations are used (in fact, the two methods have the same effect); What the global filter needs to implement is the GlobalFilter interface.

Restart the Gateway service and test it.

You can see that the custom Gateway filter is executed first, and then the global filter is executed (this order is certain and will not change).

That's all for this lecture. If you have any questions, please contact me: QQ 2100363119. Welcome to my personal website: https://www.lemon1234.com

Keywords: Spring Cloud gateway

Added by gazalec on Thu, 14 Oct 2021 05:29:32 +0300