Spring Cloud Source Analysis (iv) Zuul: Core filter

Source: Internet
Author: User
Tags types of filters

I believe you have a basic understanding of spring cloud Zuul through the article "Spring Cloud Building MicroServices Architecture (v) Service Gateway" previously released. Our first impressions of Zuul are usually as follows: it contains two functions for routing and filtering requests, in which the routing function is responsible for forwarding external requests to specific microservices instances, which is the basis for implementing external access to the unified portal, while the filter function is responsible for intervening the processing of requests. Is the basis of the functions such as request validation and service aggregation. In fact, however, when the routing function is actually running, its route mapping and request forwarding are done by several different filters. The route map is mainly done by pre-type filters, which match the request path with the configured routing rules to find the destination address to be forwarded, while the part of the request forwarding is done by the route type filter to forward the routing address obtained by the pre type filter. Therefore, the filter can be said to be Zuul implementation of the API gateway function of the most core components, each incoming Zuul HTTP request will go through a series of filter processing chain to get the request response and return to the client.

Below, let's take a look at spring Cloud Zuul's filters in detail here! The following excerpt from the "Spring Cloud micro-service combat", a little processing.

Filter filters

The filters implemented in spring Cloud Zuul must contain 4 basic features: Filter type, execution order, execution condition, and specific operation. These elements look very familiar, and in fact it is the four abstract methods defined in the Zuulfilter interface:

FilterType();

Filterorder();

Shouldfilter();

Run();

Their respective meanings and functions are summarized as follows:

    • FilterType: The function needs to return a string representing the type of the filter, which is the various stages defined during the HTTP request. The filter types for four different lifecycles are defined by default in Zuul, as follows:
      • Pre: can be called before the request is routed.
      • Routing: Called when a request is routed.
      • Post: Called after the Routing and error filters.
      • Error: Called when a request is processed when a fault occurs.
    • Filterorder: Defines the order in which the filters are executed by an int value, and the smaller the value the higher the priority.
    • Shouldfilter: Returns a Boolean type to determine whether the filter is to be executed. We can use this method to specify the effective range of the filter.
    • Run: The specific logic of the filter. In this function, we can implement the custom filtering logic to determine whether to intercept the current request, not to follow the route, or to do some processing after the request route returns the result.
Request Life cycle

In the previous section, for the filter type FilterType in spring Cloud Zuul, we've already done some simple introductions, and Zuul defines four different filter types by default, overwriting an external HTTP request to the API gateway. Until the entire life cycle of the request result is returned. A diagram of the request lifecycle from the official wiki of Zuul, which describes the detailed process of how an HTTP request flows between different types of filters after it reaches the API gateway.

Official diagram of the request life cycle

From this, we can see that when an external HTTP request arrives at the API Gateway service, it first enters the first stage of the pre, where it is processed by the pre-type filter, and the main purpose of this type of filter is to do some pre-processing before the request is routed, such as the checksum of the request. After the pre-type filter processing has been completed, the request enters the second phase of routing, which is called the routing request forwarding phase, the request will be processed by the routing type filter, where the specific processing is to forward the external request to the specific service instance process, When the service instance returns the request results, the routing phase completes and the request enters the third stage post, at which point the request is processed by the post type filter, which not only obtains the request information but also obtains the return information of the service instance. So in the Post type filter, we can do some processing or conversion of the processing results. In addition, there is a special phase error, which will only be triggered when an exception occurs in the above three phases, but its final flow is still a post type filter because it needs to return the final result to the requesting client via the post filter (there are some differences in the actual implementation, followed by).

Core Filter

In spring Cloud Zuul, in order to make API gateway components easier to use, it implements a batch of core filters by default at various stages of the HTTP request lifecycle, which are automatically loaded and enabled when the API Gateway service is started. We can view and understand them in the source code, which are defined under the Org.springframework.cloud.netflix.zuul.filters package of the Spring-cloud-netflix-core module.

The core filter for the default implementation

As shown in the filter that is enabled by default, contains three different lifecycle filters, which are important to help us understand the process of Zuul to external request processing, and how we can extend the filter on this basis to complete our own system needs. Below, we will make a detailed introduction to these filters on a case-by-case basis:

Pre Filter
  • Servletdetectionfilter: Its execution order is-3, which is the first filter to be executed. The filter is always executed, primarily to detect whether the current request is running through spring's dispatcherservlet processing or through Zuulservlet. Its test results are stored in the Isdispatcherservletrequest parameter of the current request context in the Boolean type, so that in subsequent filters we can pass the Requestutils.isdispatcherservletrequest () and the Requestutils.iszuulservletrequest () method to determine its implementation to do different processing. In general, external requests sent to the API gateway are handled by spring's dispatcherservlet, except that requests accessed through the/zuul/path bypass Dispatcherservlet and are processed by Zuulservlet. Mainly used to deal with large file upload situation. In addition, for Zuulservlet access path/zuul/, we can modify it by Zuul.servletpath parameters.
  • Servlet30wrapperfilter: Its execution order is-2, which is the second filter to execute. The current implementation will take effect for all requests, primarily to wrap the original httpservletrequest into a Servlet30requestwrapper object.
  • Formbodywrapperfilter: Its execution order is-1, which is the third filter to execute. The filter takes effect only for two kinds of requests, the first class is content-type for application/x-www-form-urlencoded, and the second class is content-type for multipart/ Form-data and is a request processed by spring's dispatcherservlet (using the results of the servletdetectionfilter processing). The main purpose of the filter is to wrap the requested body into a Formbodyrequestwrapper object.
  • Debugfilter: Its execution order is 1, which is the fourth filter to execute. The filter determines whether the action in the filter is performed based on the configuration parameters zuul.debug.request and the debug parameters in the request. Its specific operation is to set the debugrouting and Debugrequest parameters in the current request context to true. Because these two values can be accessed in different lifecycles of the same request, we can use these values in subsequent filters to define some debug information so that when there is a problem with the online environment, the debug information can be activated by requesting parameters to help analyze the problem. In addition, for the debug parameter in the request parameter, we can also use Zuul.debug.parameter to customize.
  • Predecorationfilter: Its execution order is 5, which is the last filter to be executed in the pre stage. The filter determines whether the forward.to and Serviceid parameters exist in the current request context, and if none exists, it performs the action of the specific filter (if one exists, it indicates that the current request has been processed because the two messages are loaded based on the routing information of the current request). and its specific operation is to do some preprocessing for the current request, such as: the matching of routing rules, in the context of the request to set the basic information of the request and the route matching results, such as some settings information, such information will be the next filter to deal with the important basis, We can access this information through Requestcontext.getcurrentcontext (). In addition, we can find some logic to handle HTTP header requests in this implementation, including some familiar header fields, such as: X-forwarded-host, X-forwarded-port. In addition, the records for these header fields are controlled by the Zuul.addproxyheaders parameter, and this parameter defaults to true, so Zuul adds the x-forwarded-* header field to the request by default when the request jumps. Including: X-forwarded-host, X-forwarded-port, X-forwarded-for, X-forwarded-prefix, X-forwarded-proto. We can also turn off adding actions to these header fields by setting Zuul.addproxyheaders=false.

Spring Cloud Practical Tips: Zuul handling cookies and redirects the load sensitive header information added to the Ignore header information is implemented in the Predecorationfilter filter.

Route Filter
    • Ribbonroutingfilter: Its execution order is 10, which is the first filter to be executed in the route stage. This filter only processes requests that have the Serviceid parameter in the context of the request, that is, only the request to configure the routing rule through Serviceid takes effect. The execution logic of this filter is the core of service-oriented routing, which uses the Ribbon and hystrix to initiate requests to the service instance and returns the result of the service instance's request.
    • Simplehostroutingfilter: Its execution order is 100, which is the second filter to be executed in the route stage. The filter only processes requests that have the Routehost parameter in the context of the request, that is, only the request to configure the routing rule through the URL takes effect. And the execution logic of the filter is directly to the Routehost parameter of the physical address of the request, from the source we can know that the request is directly through the HttpClient package implementation, and not using the Hystrix command to wrap, so such requests are not thread isolation and circuit breaker protection.
    • Sendforwardfilter: Its execution order is 500, which is the third filter to be executed in the route stage. This filter only processes requests that have the forward.to parameter in the context of the request, which is used to handle the forward local jump configuration in the routing rule.
Post Filter
    • Senderrorfilter: Its execution order is 0, which is the first filter to be executed in the post phase. The filter is executed only if the request context contains the Error.status_code parameter (the error code set by the previously executed filter) and has not been processed by the filter. The specific logic of the filter is to use the error information in the context of the request to organize a request to forward to the API Gateway/error error endpoint to generate an error response.
    • Sendresponsefilter: Its execution order is 1000, which is the last filter to be executed in the post phase. The filter checks whether the request context contains header information related to the request response, the response data stream, or the response body, and the processing logic is executed only when one of them is included. The processing logic of the filter is to use the response information of the request context to organize the response content that needs to be sent back to the client.

no specific code is listed here, the reader can view the source code according to the class name to understand the detailed processing process. is the above filter based on the order, name, function, type of comprehensive collation, can help us in the custom filter or extended filter when used to refer to and comprehensively consider the entire request life cycle of the processing process.

Core Filter Summary

This article excerpt from the "Spring Cloud micro-service combat", some slightly processing, reproduced please indicate the source

Spring Cloud Source Analysis (iv) Zuul: Core filter

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.