Spring Cloud (DALSTON.SR5)--zuul Gateway-Filter

Source: Internet
Author: User
Tags types of filters

Spring Cloud provides multiple filters for each phase of an HTTP request, the order of execution of which is determined by an int value provided, the smaller the value, the higher the priority, and the default filter and priority as follows:

Custom Filters

On the basis of the default filter, we can implement our own custom filters, custom filters need to inherit the Com.netflix.zuul.ZuulFilter class, and implement the relevant methods, described 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 routing a request
      • Post: Called after the Routing and Error filters
      • Error: Called when processing a request
    • Filterorder: Defines the order in which the filters are executed by an int value, 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.

Zuul defines four different filter types by default, overwriting an external HTTP request to the API gateway until the full lifecycle of the request result is returned. The graphical representation of the request lifecycle from the official wiki of Zuul, which describes how the detailed process of transferring the various types of filters after an HTTP request arrives at the API gateway is as follows:

As we can see, 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 the post Type of filter, we can do some processing or conversion of the results of processing and other content.

In addition, there is a special phase error, which is only triggered when an exception occurs in the above three stages, but its final flow is the post type filter because it needs to return the final result to the requesting client via the post filter.

??

Filter examples

  • Validation Filters

    The filter executes at the pre stage, and its priority is 1 after the wrapper request body executes, its shouldfilter returns true to indicate that the filter is executed in any case, and the Run method obtains the request parameter and validates it by getting the httpservletrequest example, validating Failure is done by setting the HttpServletResponse example and Setsendzuulresponse (false) to return the response information directly, without subsequent filter processing.

    Package Org.lixue.zuul;

    ??

    Import Com.netflix.zuul.ZuulFilter;

    Import Com.netflix.zuul.context.RequestContext;

    Import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;

    ??

    Import javax.servlet.http.HttpServletRequest;

    Import Javax.servlet.http.HttpServletResponse;

    Import java.io.IOException;

    ??

    Public class tokenprezullfilter extends zuulfilter{

    @Override

    Public String FilterType () {

    return Filterconstants.pre_type;

    }

    ??

    @Override

    public int Filterorder () {

    return 1;

    }

    ??

    @Override

    Public Boolean Shouldfilter () {

    return True ;

    }

    ??

    @Override

    Public Object Run () {

    RequestContext Ctx=requestcontext.getcurrentcontext ();

    HttpServletRequest request=ctx.getrequest ();

    System.out.println (String.Format ("%s request to%s", Request.getmethod (), Request.getrequesturl (). ToString ());

    String Token=request.getparameter ("token");

    System.out.println ("token:"+token);

    if (token==null| |! Token.equals ("Success_token")) {

    Authentication failed

    System.out.println ("token verification failed");

    HttpServletResponse Response=ctx.getresponse ();

    Response.setcharacterencoding ("Utf-8"); Set character sets

    Response.setcontenttype ("Text/html;charset=utf-8"); Set the appropriate format

    Response.setstatus (401);

    Ctx.setsendzuulresponse (false); Do not route

    Try {

    Response.getwriter (). Write ("token verification failed"); Response Body

    }catch(ioexceptione) {

    System.out.println ("Responseio anomaly");

    E.printstacktrace ();

    }

    Ctx.setresponse (response);

    return null ;

    }

    System.out.println ("token verification Success");

    return null ;

    }

    }

    ??

  • Filter Configuration Class

    In order for the Spring container to know the existence of a filter, you need to configure the class, create a filter configuration class, use annotations @Configuration label classes, and use @Bean annotation labels to return the method of the filter.

    Package Org.lixue.zuul;

    ??

    Import org.springframework.context.annotation. Bean;

    Import org.springframework.context.annotation. Configuration;

    ??

    @Configuration

    Public class zuulfilterconfiguration{

    ??

    @Bean

    Public Tokenprezullfilter Tokenprezullfilter () {

    return new Tokenprezullfilter ();

    }

    }

    ??

  • Test validation

    The project relies on a eureka-sserver, Service-provider service that starts the Eureka-server and Service-provider services first, and then starts Spring-cloud-zuul-microservices service, access to Http://localhost:9200/hello/speaks?names=123&token=success_token address, can be seen to return normally, as follows:

    {"123": "Hello World 123 port=8080"}

    Modify the access address, remove the token parameter, or modify the parameter value http://localhost:9200/hello/speaks?names=123&token=success_token999 this will return token Validation of failed errors, and no subsequent route processing is performed.

Spring Cloud (DALSTON.SR5)--zuul Gateway-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.