springcloud distributed micro service E-commerce mall learn from me about the use of spring cloud gateway filter factory

Gateway filter factory is a filter factory provided in Spring Cloud Gateway. The routing filter of Spring Cloud Gateway allows you to modify the incoming HTTP request or output HTTP response in some way, which only works on specific routes.

Spring Cloud Gateway has many built-in filter factories, which can be used directly by configuration. At the same time, it also supports custom GatewayFilter Factory to realize more complex business requirements.

spring:
  cloud:
    gateway:
      routes:
        - id: add_request_header_route
  uri: http://c.biancheng.net
  filters:
    - AddRequestHeader=X-Request-Foo, Bar

Next, let's introduce several commonly used filter factory classes.

1. AddRequestHeader filter factory

Through the name, we can quickly understand that the function of this filter factory is to add request headers.

For the request that meets the rule and matches successfully, the X-Request-Foo: bar request header will be added and passed to the back-end service, and the rear service can directly obtain the request header information. The code is shown below.

@GetMapping("/hello")
public String hello(HttpServletRequest request) throws Exception {
    System.err.println(request.getHeader("X-Request-Foo"));
    return "success";
}

2. RemoveRequestHeader filter factory

Removerequeheader is a filter factory that removes the request Header. You can remove the Header before the request is forwarded to the back-end service.

spring:
  cloud:
    gateway:
      routes:
  - id: removerequestheader_route
  uri: http://c.biancheng.net
    - RemoveRequestHeader=X-Request-Foo

3. SetStatus filter factory

The SetStatus filter factory receives a single status and is used to set the response code of the HTTP request. It must be a valid Spring Httpstatus (org.springframework.http.HttpStatus). It can be an integer value 404 or an enumeration type NOT_FOUND.

spring:
  cloud:
    gateway:
      routes:
        - id: setstatusint_route
  uri: http://c.biancheng.net
  filters:
    - SetStatus=401

4. RedirectTo filter factory

RedirectTo filter factory is used for redirection. For example, we need to redirect to Baidu.

spring:
  cloud:
    gateway:
      routes:
        - id: prefixpath_route
  uri: http://c.biancheng.net
  filters:
    - RedirectTo=302, http://baidu.com

The above introduces the use of several filter factories. Later in the tutorial, we will introduce Retry, RequestRateLimiter current limiting, Hystrix fuse filter factory and other contents. Others can refer to the official documents for learning.

Custom Spring Cloud Gateway filter factory

To customize the Spring Cloud Gateway filter factory, you need to inherit the AbstractGatewayFilterFactory class and override the logic of the apply method. The name needs to end with GatewayFilterFactory, such as CheckAuthGatewayFilterFactory. When used, CheckAuth is the name of the filter factory.

The custom filter factory code is shown below.

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

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

    @Override
    public GatewayFilter apply(Config config) {
    return (exchange, chain) -> {
      System.err.println("Entered CheckAuth2GatewayFilterFactory" + config.getName());
      ServerHttpRequest request = exchange.getRequest().mutate()
      .build();
      return
      chain.filter(exchange.mutate().request(request).build());
    }
  }

    public static class Config {
        private String name;

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

        public String getName() {
            return name;
        }
    }
}

Use the following:

filters:
  - name: CheckAuth2
  args:
    name: Zhang San

If your configuration is in the form of Key and Value, you can directly inherit the AbstractNameValueGatewayFilterFactory class without defining your own configuration class.

AbstractNameValueGatewayFilterFactory class inherits AbstractGatewayFilterFactory and defines a NameValueConfig configuration class. NameValueConfig has two fields: name and value.

We can use it directly. AddRequestHeaderGatewayFilterFactory and AddRequestParameterGatewayFilterFactory are all AbstractNameValueGatewayFilterFactory directly inherited.

Define the filter factory by inheriting AbstractNameValueGatewayFilterFactory. The code is as follows.

@Component
public class CheckAuthGatewayFilterFactory extends AbstractNameValueGatewayFilter-actory {
    @Override
    public GatewayFilter apply(NameValueConfig config) {
        return (exchange, chain) -> {
            System.err.println("Entered CheckAuthGatewayFilterFactory" + config.getName() + "\t" + config.getValue());
            ServerHttpRequest request = exchange.getRequest().mutate().build();
            return chain.filter(exchange.mutate().request(request).build());
        };
    }
}

Use the following:

filters: 
        - CheckAuth=zhangsan,male

Recommended e-commerce source code

Keywords: Spring Spring Cloud

Added by lancia on Tue, 08 Mar 2022 19:51:30 +0200