Daily Record Internet Items - - 5(Zuul, Filter, Integrated Ribbon,Hystrix)

6. Zuul Gateway

6.1 Introduction

  • Zuul is the unified gateway to our services

  • Whether it's a request from a client (PC or mobile) or an internal call to a service.

  • All requests for services go through the Zuul gateway, which then implements authentication, dynamic routing, and so on.

6.2 Getting started with Zuul

Actual path: http://localhost:8081/test

Expected path: http://localhost:10010/api/service/test
		  http://localhost:10010/path prefixed/service name/controller access path			
  • Step 1: Import pom dependencies

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-zuul</artifactId>
        </dependency>
    </dependencies>
    
  • Step 2: Turn on the zuul service

    @SpringBootApplication
    @EnableZuulProxy
    public class ZuulApplication {
        public static void main(String[] args) {
            SpringApplication.run(ZuulApplication.class,args);
        }
    }
    
  • Step 3: Modify the yml file

    server:
      port: 10010
    spring:
      application:
        name: zuul_demo
    zuul:
      prefix: /api  #Routing Prefix
      routes:
        service: /service/**
          path: /service/**
          url: http://localhost:8081
    

6.2 Routing Oriented

  • The yml file writing above kills the access path and changes it to service name access

  • Step 1: Modify the pom dependency

    <!--Add to eureka Client-->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    </dependency>
    
  • Step 2: Open the eureka client

    @SpringBootApplication
    @EnableZuulProxy
    @EnableEurekaClient
    public class ZuulApplication {
        public static void main(String[] args) {
            SpringApplication.run(ZuulApplication.class,args);
        }
    }
    
  • Step 2: Modify the yml file, register yourself with the registry, and access it through the service name

    • Once registered with the registry, the service name is automatically accessed through Ribbon, and access paths can be omitted from writing
    server:
      port: 10010
    spring:
      application:
        name: zuul
    eureka:
      client:
        service-url:
          defaultZone: http://localhost:10087/eureka/
      instance:
        instance-id: ${spring.application.name}:${spring.cloud.client.ip-address}:${server.port}
        prefer-ip-address: true
    zuul:
      prefix: /api	#Routing Prefix
    

6.3 Filter

  • One of the important functions of Zuul as a gateway is to enable authentication of requests.
  • This is often achieved through filters provided by Zuul

6.3.1 ZuulFilter

  • ZuulFilter is the top-level parent of a filter, with four methods

    public abstract ZuulFilter implements IZuulFilter{
        		abstract public String filterType(); 	//Filter type
        		abstract public int filterOrder();		//Execution order
        		boolean shouldFilter();					//Is Execution Needed
        		Object run() throws ZuulException;		//Specific business logic
    }
    
    • shouldFilter: Returns a Boolean value to determine if the filter needs to be executed.Return true execution, return false does not execute
    • FiltererType: Returns a string representing the type of filter.There are four types:
      • pre: Request executed before being routed
      • routing: called on route request
      • post: called after routing and errror filters
      • Error: an error call occurred while processing the request
    • FiltererOrder: Defines the execution order of the filter by returning an int value. The smaller the number, the higher the priority.
    • run: The specific business logic of the filter.

    6.3.1 Getting Started with Filters

    • Create a test class and inherit ZuulFilter

      package com.czxy.filter;
      
      import com.netflix.zuul.ZuulFilter;
      import com.netflix.zuul.context.RequestContext;
      import com.netflix.zuul.exception.ZuulException;
      import org.springframework.stereotype.Component;
      
      import javax.servlet.http.HttpServletRequest;
      
      @Component
      public class LoginFilter extends ZuulFilter {
          @Override
          public String filterType() {//  Setting Type
              return "pre";
          }
      
          @Override
          public int filterOrder() {//  Set Sort
              return 1;
          }
      
          @Override
          public boolean shouldFilter() {//  Execute or not
              return true;
          }
      
          @Override
          public Object run() throws ZuulException {
              //1, Get the context object
              RequestContext requestContext = RequestContext.getCurrentContext();
              //2, get the request object
              HttpServletRequest request = requestContext.getRequest();
              //3, get the check request header
              String token = request.getHeader("Authorization");
              //4. Determine if there is any
              if (token == null){
                  //4.1 Turn off response
                  requestContext.setSendZuulResponse(false);
                  //4.2 Return status code
                  requestContext.setResponseStatusCode(401);
              }
              //5, Release
              return null;
          }
      }
      

6.4 Load Balancing and Fusing

  • Ribbon load balancing and Hystix fusing mechanisms are already integrated by default in Zuul.

    #Gateway Configuration
    zuul:
      retryable: true   #Turn on retry (Note: Check if zuul was configured before, and if configuration requires merging configuration items)
    
    #Global Load Balancing Configuration
    ribbon:
      ConnectTimeout: 250 # Connection timeout (ms)
      ReadTimeout: 2000 # Communication timeout (ms)
      OkToRetryOnAllOperations: true # Whether to retry all operations
      MaxAutoRetriesNextServer: 2 # Number of retries for different instances of the same service
      MaxAutoRetries: 1 # Number of retries for the same instance
    #Fuse
    hystrix:
      command:
       default:
            execution:
              isolation:
                thread:
                  timeoutInMillisecond: 6000 # Fuse timeout: 6000ms
    

Keywords: Programming Spring Mobile

Added by I WanT To Code PHP on Sat, 14 Dec 2019 09:50:30 +0200