Detailed explanation of gateway filter

what is filter

In Spring Cloud, filters are a key component used to process and transform incoming requests and outgoing responses in a microservice architecture. Filters reside in a service gateway or proxy and provide various functions by intercepting request and response traffic.

Filters perform specific operations at different life cycle stages of the request, such as authentication, certification, request forwarding, current limiting, logging, etc. They can be configured and applied at different points in the service call chain to implement various requirements and business rules.

Spring Cloud Gateway and Zuul are two commonly used Spring Cloud components that provide built-in filter mechanisms.

Spring Cloud Gateway uses GatewayFilter to define filters. GatewayFilter can perform operations when the request enters the gateway, before or after routing forwarding, and before or after the response is returned to the client. They provide rich functions and scalability, such as authentication, current limiting, retry, request forwarding, request/response modification, etc.

Zuul uses Zuul Filter to implement filter functions. Zuul Filter is divided into four types: pre, route, post and error. The pre filter is executed before the request is routed and can be used for operations such as authentication and request restriction; the route filter is used to route the request to a specific service instance; the post filter is executed after the request has been routed to the target service and a response has been obtained. It can perform operations such as response logging and statistics collection; the error filter handles errors that occur throughout the request life cycle.

By writing and configuring filters, we can operate on requests and responses based on specific needs, enabling powerful functionality and logic. Filters can improve security, stability, and maintainability, and are integrated with other components of Spring Cloud to make the microservice architecture more flexible and scalable.

Type of filter

In Spring Cloud, filters can be divided into the following types according to their role and stage:

Global Filters: Global filters are filters that apply to all requests and responses entering a service gateway or proxy. They can perform common functions across services, such as authentication, request logging, performance monitoring, etc. Global filters have a global impact on the entire microservice architecture, so they need to be used with caution.

Pre Filters: Pre filters are executed before route forwarding. They can handle request verification, authentication, parameter verification and other operations. Pre-filters can intercept requests and make necessary modifications, such as adding header information, modifying request paths, etc. With pre-filters, we can preprocess requests before they enter the system.

Route Filters: Route filters are executed before the request is routed to the target service instance. They can modify the request's URL, request headers, request body, etc., and decide which service instance the request should be routed to. Through routing filters, we can implement dynamic routing, load balancing and other functions.

Post Filters: Post filters are executed after the request has been routed to the target service instance and a response has been obtained. They can perform processing on responses, such as logging, converting results, adding response headers, etc. Post-filters are often used to process responses uniformly to ensure that responses comply with unified formats and standards.

Error Filters: Error filters are used to handle errors that occur during the request life cycle. They can catch exceptions, log error messages, and provide appropriate responses to clients. Error filters can make your system more robust, making it better able to handle exceptions.

Except for global filters, all others are local filters.

local filter

Local Filters refer to filters applied to specific routes or service instances. They can be processed for a specific route and only take effect on requests and responses to that route. Post-filters are a form of local filters that are executed after the request is routed to the target service instance and a response is obtained.

By defining post-filters, you can process and modify responses returned from backend services. For example, you can add response headers, log, convert response results, and other operations in post-filters. Post-filters provide an opportunity to process the response during the final stages of the request lifecycle.

code example

The following is an example of a routing filter

import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.stereotype.Component;

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

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

    @Override
    public GatewayFilter apply(Config config) {
    
    
        return (exchange, chain) -> {
    
    
            // 在路由请求之前执行的操作
            System.out.println("执行路由过滤器");
            // 可以根据需要对请求进行修改、验证等操作

            return chain.filter(exchange);
        };
    }

    public static class Config {
    
    
        // 配置参数(可选)
    }

}

In the above example, we created a class called CustomRouteFilter and inherited AbstractGatewayFilterFactory. Likewise, Config is a class used for configuration parameters, customized as needed.

Then, we overridden the apply method and wrote custom routing filter logic in it. In this example, we simply print a message indicating that the route filter was executed.

By adding this custom routing filter to Spring Cloud Gateway's routing configuration, it will perform specific logic before routing the request. You can also modify and verify the request as needed.

global filter

A global filter is a filter that is applied to all requests and responses entering a service gateway or proxy. They can perform common functions across services, such as authentication, request logging, performance monitoring, etc. Global filters have a global impact on the entire microservice architecture, so they need to be used with caution.

code example

In the global filter, the filtered class needs to implement the GlobalFilter interface.

@Component
public class LogFilter implements GlobalFilter {
    
    
    Logger log=  LoggerFactory.getLogger(this.getClass());
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
    
    
        log.info(exchange.getRequest().getPath().value());
        return chain.filter(exchange);
    }
}

This code is a global filter for logging. When executed, its corresponding log information will be recorded on the console.
Insert image description here

Summarize

As an important component in Spring Cloud Gateway, Filter can process incoming HTTP requests in order to modify or validate them, or perform specific logic before/after routing to the target service. Filter is the core part of Gateway, used to provide a common mechanism to handle HTTP requests and help achieve a more powerful, efficient and secure gateway.

Spring Cloud Gateway provides three different types of Filters: global filters, local pre-filters and local post-filters. Among them, global filters will apply to all routes, while local filters will only apply to specified routes.

By customizing Filter, we can achieve a variety of custom needs. For example, we can create an authentication filter for a specific request path to verify whether the user has the permission to access the corresponding resource; we can also write a logging Filter to output relevant log information before/after the request is routed to the target service.

The steps for writing a custom Filter usually include the following points:

Create a Filter class that inherits AbstractGatewayFilterFactory.
Override the apply method in the Filter class and write custom logic.
Configure the required parameters in the Filter class (optional).
Add Filter in the routing configuration of Spring Cloud Gateway.
Of course, adjustments need to be made according to actual needs, such as defining filters of different types and granularities, etc.

In short, Filters provide a flexible, reliable, and scalable mechanism to cope with various needs. When developing a gateway, Filter is a very important component, which plays an important role in ensuring efficiency and scalability.

Guess you like

Origin blog.csdn.net/weixin_45309155/article/details/133138544