Article From:https://www.cnblogs.com/fengyan20150508/p/9970330.html

I. Zuul’s Characteristics

  zuulIt has the following functions:

  • Authentication
  • Insights
  • Stress Testing
  • Canary Testing
  • Dynamic Routing
  • Service Migration
  • Load Shedding
  • Security
  • Static Response handling
  • Active/Active traffic managemen

2. Brief introduction of Spring-Clound project architecture

  

  ZuulIt is a gateway, which forwards access requests to various micro-service systems according to routing rules to complete the customer’s request response. It is equivalent to a traffic management boom, so it can filter and forward requests.

III. Zuul Framework

 

  

  zuulIt provides a framework for dynamic loading, compiling and running of filters. There is no direct communication between filters. They pass data through a static class of RequestContext. There is Thread in the RequestContext classLocal variables to record the requirements for each Request

IV. Zuul’s filters

 

  4.1 Types of filters

  •   PRE:This filter is called before the request reaches Origin Server. For example, authentication, selecting Origin Server for requests in the cluster, logging, etc., is the filter used in workshop.
  • ROUTING:In this filter, user requests are sent to Origin Server. User requests sent to Origin Server are built in such filters. And use Apache HttpClient or Netfilx Ribbon to sendTo Origin Server.
  • POST:This filter is executed after the user requests to return from Origin Server. For example, add a response header on the response returned, do various statistics, etc. In this filter, the response is returned to the customer.
  • ERROR:Execute the filter when errors occur at other stages.
  • Customer customization: For example, we can customize a STATIC type filter to simulate the generation of responses returned to customers.
  1. Life cycle of filter

  

 

  A request passes through all the pre-filters in sequence, then forwards to the back-end application in the routing filter, gets the response, then passes through all the post-filters, and finally responds to the client. If an exception occurs throughout the process, it jumps to the error filter.

 

V. Application of Zuul

  Continue to use the previous section of the project. On the original project, create a new project Zuul.     

   5.1 Add dependency

<dependency>
     <groupId>org.springframework.cloud</groupId>
     <artifactId>spring-cloud-starter-netflix-zuul</artifactId>
</dependency>

  5.2 Add the annotation @EnableZuulProxy to the application Caton class at its entry to turn on Zuul’s function:

  

@EnableZuulProxy
@EnableEurekaClient
@SpringBootApplication
public class ServiceZuulApplication {

    public static void main(String[] args) {
        SpringApplication.run(ServiceZuulApplication.class, args);
    }



}

  5.3 Adding zuul related configuration

  

eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/
server:
  port: 8769
spring:
  application:
    name: service-zuul
zuul:
  routes:
    api-a:
      path: /api-a/**
      serviceId: service-ribbon
    api-b:
      path: /api-b/**
      serviceId: service-feign

  5.4 Add a filter

@Component
public class MyFilter extends ZuulFilter{

    private static Logger log = LoggerFactory.getLogger(MyFilter.class);
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        log.info(String.format("%s >>> %s", request.getMethod(), request.getRequestURL().toString()));
        Object accessToken = request.getParameter("token");
        if(accessToken == null) {
            log.warn("token is empty");
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(401);
            try {
                ctx.getResponse().getWriter().write("token is empty");
            }catch (Exception e){}

            return null;
        }
        log.info("ok");
        return null;
    }
}

  5.5 Start in turn, so the project is as follows:

 

   Review: Firstly, the address of the service registry is specified as http://localhost:8761/eureka/, the port of the service is 8769, and the service name is service-zuul; all requests starting with/api-a/are forwarded to service.- ribbon service; requests starting with / api-b / are forwarded to service-feign service;

Leave a Reply

Your email address will not be published. Required fields are marked *