Take you to quickly understand the microservice gateway!

Posted by jotgabbi on Tue, 08 Mar 2022 19:16:13 +0100

Gateway concept

Gateway is also known as inter network connector and protocol converter. Gateway realizes network interconnection above the network layer. It is a complex network interconnection device, which is only used for the interconnection of two networks with different high-level protocols. Gateway can be used for both Wan interconnection and LAN interconnection. Gateway is a computer system or device that acts as a conversion task. The gateway is a translator used between two systems with different communication protocols, data formats or languages, or even completely different architectures. Unlike the bridge that simply conveys information, the gateway repackages the received information to meet the needs of the target system. The gateway in microservice is used to handle external requests and distribute them to internal services to control the distribution of external traffic!

Introduction to zuul gateway

Zuul is a member of Netflix OSS. It is a load balancer based on JVM routing and server. Provide a service framework in terms of routing, monitoring, elasticity and security. Zuul can be used with Eureka, Ribbon, Hystrix and other components.

Introduction to main functions of zuul

  1. Dynamic routing

Dynamically route the client's requests to different back-end services and do some logical processing, such as aggregating the data return of multiple services.

  1. Request monitoring

It can monitor the request of the whole system, record the detailed request response log, and count the current system access and monitoring status in real time.

  1. Authentication

Authenticate every access request, reject illegal requests and protect the back-end services.

  1. Pressure test

Stress testing is a very important work. For example, some e-commerce companies need to simulate more real user concurrency to ensure the stability of the system during major activities. Zuul can dynamically forward requests to the cluster of back-end services, and can also identify test traffic and real traffic, so as to do some special processing.

  1. Gray Publishing

Gray level release can ensure the stability of the overall system. Problems can be found and adjusted at the initial gray level to ensure its influence.

zuul principle

Most of zuul's functions are realized through filters. Zuul defines four standard filter types that correspond to the typical life cycle of a request.

(1) PRE: this filter is called before the request is routed. We can use this filter to realize authentication, select the requested micro service in the cluster, record debugging information, etc.

(2) ROUTING: this filter routes requests to microservices. This filter is used to build requests to microservices and request microservices using Apache HttpClient or Netfilx Ribbon.

(3) POST: this filter is executed after routing to the microservice. This filter can be used to add standard HTTP headers for responses, collect statistics and indicators, send responses from microservices to clients, and so on.

(4) ERROR: this filter is executed when errors occur in other phases.

zuul also provides a kind of built-in special filter,

(1) StaticResponseFilter: StaticResponseFilter allows responses to be generated from Zuul itself, rather than forwarding requests to the source.

(2) SurgicalDebugFilter: SurgicalDebugFilter allows specific requests to be routed to separate debug clusters or hosts.

(3) Inherit ZuulFilter custom filter

zuul custom filters,

The following mainly introduces ZuulFilter class

public class AccessUserNameFilter extends ZuulFilter {  
    @Override  
    public Object run() {  
        RequestContext ctx = RequestContext.getCurrentContext();  
        HttpServletRequest request = ctx.getRequest();  
  
        System.out.println(String.format("%s AccessUserNameFilter request to %s", request.getMethod(), request.getRequestURL().toString()));  
  
        String username = request.getParameter("username");// Get requested parameters  
        if(null != username && username.equals("chhliu")) {// If the requested parameter is not empty and the value is chhliu, the  
            ctx.setSendZuulResponse(true);// Route the request  
            ctx.setResponseStatusCode(200);  
            ctx.set("isSuccess", true);// Set the value so that the next Filter can see the status of the previous Filter  
            return null;  
        }else{  
            ctx.setSendZuulResponse(false);// Filter the request without routing it  
            ctx.setResponseStatusCode(401);// Return error code  
            ctx.setResponseBody("{\"result\":\"username is not correct!\"}");// Return error content  
            ctx.set("isSuccess", false);  
            return null;  
        }  
    }  
  
    #  If the result of the previous filter is true, it indicates that the previous filter is successful and needs to enter the current filter. If the result of the previous filter is false, it indicates that the previous filter is not successful, so there is no need to carry out the following filtering actions. Directly skip all the filters in the back and return the results  
    @Override 
    public boolean shouldFilter() {  
        RequestContext ctx = RequestContext.getCurrentContext();  
        return (boolean) ctx.get("isSuccess");
    }  
  
   
    # The priority is 0. The higher the number, the lower the priority
    @Override  
    public int filterOrder() {  
        return 0;  
    }  
  
   # Prefilter  
    @Override  
    public String filterType() {  
        return "pre";
    }  
}  

filterType: returns a string representing the filter type. Four filter types with different life cycles are defined in zuul, as follows:

  • pre: can be called before the request is routed.
  • route: called when routing a request
  • post: called after the route and error filters
  • Error: called when an error occurred while processing the request

How to use zuul in spring cloud

  1. Project configuration

  • pom introduces dependency

    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-zuul</artifactId>
    </dependency>
    
  • @EnableZuulProxy annotation

    @EnableZuulProxy
    @SpringBootApplication
    public class App {
        public static void main(String[] args) {
            SpringApplication.run(App.class, args);
        }
    }
    
  • Configure routing file

    spring.application.name=zuul-test
    server.port=8080
    
    zuul.routes.test.path=/test/**
    zuul.routes.test.url=http://c.test.com
    
  1. Detailed explanation of service routing configuration

  • Specify a specific service route

    zuul.routes.access.path=/access-name/**
    

    The above code configures the routing address of access service to access name, that is, when we need to access the interface in access, we can use access name / interface name. This is actually changing the service name into our custom name** Represents matching multi-level interfaces.

  • Routing prefix

    Sometimes we want to configure a uniform prefix in front of the API, such as http://c.biancheng.net/access/login In this way, if you want to turn it into http://c.biancheng.net/rest/access/login That is, add a rest in front of each interface. At this time, we can realize it through the configuration in Zuul:

      zuul.prefix=/rest
    
  • Local jump

    Zuul's API routing also provides local jump function, which can be realized through forward.

      zuul.routes.fsh-substitution.path=/api/**
      zuul.routes.fsh-substitution.url=forward:/local
    

    When we want to route to the local local/1 when accessing api/1, we can refer to the above code. Local is a local interface, which needs to be added by ourselves, so we need to build a Controller. The code is as follows.

    @RestController
    public class LocalController {
        @GetMapping("/local/{id}")
        public String local(@PathVariable String id) {
            return id;
        }
    }
    
  1. Filter filter (refer to filter in zuul principle)

    • How to use custom filters
      Configuration
      public class FilterConfig {
          @Bean
          public AccessUserNameFilter accessFilter() {
              return new AccessUserNameFilter();
          }
      }
    
  • How to disable custom filters

    In this case, we need to disable the filter in the following two ways:

    • Use return false in shouldFilter method to make the filter no longer execute
    • Disable the filter through configuration. The format is "zuul. Filter class name. Filter type. disable=true". If we need to disable AccessUserNameFilter in the "use filter" section, we can use the following configuration:
      zuul.AccessUserNameFilter.pre.disable=true

end

Because zuul2 The performance of 0 continuous ticket skipping and zuul1 is not very ideal, so the spring team developed the Gateway project. The next part introduces the Spring cloud gateway

Welcome to the official account!
The official account reply: join the group, sweep the code to join our communication group!

Topics: Spring Cloud Microservices gateway microservice