Home  >  Article  >  Java  >  Introduction to the principles and usage of zuul in SpringCloud

Introduction to the principles and usage of zuul in SpringCloud

不言
不言forward
2019-04-11 13:18:397647browse

This article brings you an introduction to the principles and usage of zuul in Spring Cloud. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Introduction

Zuul is the front door for all requests from devices and web sites to the backend of the Netflix streaming application. As an edge services application, Zuul is built to support dynamic routing, monitoring, resiliency and security. It can also route requests to multiple Amazon Autoscaling groups as needed.

Zuul uses a series of different types of filters to allow us to quickly and flexibly apply functionality to edge services. These filters help us perform the following functions:

  • Authentication and Security - Identify the authentication requirements for each resource and reject requests that do not meet those requirements.
  • Insights and Monitoring – Track meaningful data and statistics at the edge to give us an accurate view of production.
  • Dynamic Routing - Dynamically routes requests to different backend clusters as needed.
  • Stress Test - Gradually increase traffic to the cluster to evaluate performance.
  • Reduce load - allocate capacity to each type of request and remove requests that exceed the limit.
  • Static response handling - build some responses directly at the edge instead of forwarding them to the internal cluster
  • Multi-region resiliency - route requests across AWS regions to make our ELB usage diverse ization and bringing our strengths closer to our members

How it works

In high-level view, Zuul 2.0 is a Netty server that runs a pre-filter ( Inbound filter) and then proxy the request using Netty client and then return the response after running the post filter (Outbound filter).

Introduction to the principles and usage of zuul in SpringCloud

#Filters are the core of Zuul's business logic. They are capable of performing a very wide range of operations and can operate in different parts of the request-response life cycle, as shown in the diagram above.

  • Inbound Filters are executed before routing to the source and can be used for authentication, routing and decorating requests.
  • Endpoint Filters can be used to return static responses, otherwise the built-in ProxyEndpoint filter will route the request to the origin.
  • Outbound Filters are executed after getting the response from the source and can be used to measure, decorate the user response, or add custom headers.

There are also two types of filters: Synchronous and asynchronous . Because we are running on an event loop, never block the filter. If you want to block, you can block in an asynchronous filter, blocking on a separate threadpool - otherwise use a synchronous filter.

Utility Filters

  • DebugRequest - Find a query parameter to add additional debug logs to the request
  • Healthcheck - Simple static endpoint filter that returns 200 if everything bootstrapped correctly
  • ZuulResponseFilter - Adds information headers to provide additional details about routing, request execution, status and error reason
  • GZipResponseFilter - Can enable gzip Outbound response
  • SurgicalDebugFilter - specific requests can be routed to different hosts for debugging

Usage tips

Dependencies:

    <dependency>
            <groupid>org.springframework.cloud</groupid>
            <artifactid>spring-cloud-starter-netflix-zuul</artifactid>
        </dependency>

MyFilter filter

@Component
public class MyFilter extends ZuulFilter {

    private static Logger log = LoggerFactory.getLogger(MyFilter.class);

    /**
     * pre:路由之前
     * routing:路由之时
     * post: 路由之后
     * error:发送错误调用
     * @return
     */
    @Override
    public String filterType() {
        return "pre";
    }

    /**
     * 过滤的顺序
     * @return
     */
    @Override
    public int filterOrder() {
        return 0;
    }

    /**
     * 这里可以写逻辑判断,是否要过滤,本文true,永远过滤
     * @return
     */
    @Override
    public boolean shouldFilter() {
        return true;
    }


    /**
     * 过滤器的具体逻辑。
     * 可用很复杂,包括查sql,nosql去判断该请求到底有没有权限访问。
     * @return
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {
        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;
    }

}

application.yml configuration routing forwarding

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

Enable zuul

@SpringBootApplication
@EnableZuulProxy
@EnableEurekaClient
@EnableDiscoveryClient
public class CloudServiceZuulApplication {

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

}

Route meltdown

/**
 * 路由熔断
 */
@Component
public class ProducerFallback implements FallbackProvider {
    private final Logger logger = LoggerFactory.getLogger(FallbackProvider.class);

    //指定要处理的 service。
    @Override
    public String getRoute() {
        return "spring-cloud-producer";
    }

    @Override
    public ClientHttpResponse fallbackResponse(String route, Throwable cause) {
        if (cause != null && cause.getCause() != null) {
            String reason = cause.getCause().getMessage();
            logger.info("Excption {}",reason);
        }
        return fallbackResponse();
    }

    public ClientHttpResponse fallbackResponse() {
        return new ClientHttpResponse() {
            @Override
            public HttpStatus getStatusCode() throws IOException {
                return HttpStatus.OK;
            }

            @Override
            public int getRawStatusCode() throws IOException {
                return 200;
            }

            @Override
            public String getStatusText() throws IOException {
                return "OK";
            }

            @Override
            public void close() {

            }

            @Override
            public InputStream getBody() throws IOException {
                return new ByteArrayInputStream("The service is unavailable.".getBytes());
            }

            @Override
            public HttpHeaders getHeaders() {
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_JSON);
                return headers;
            }
        };
    }


}

Summary

Zuul gateway has an automatic forwarding mechanism, but in fact Zuul has more application scenarios, such as : Authentication, traffic forwarding, request statistics, etc. These functions can all be implemented using Zuul.


The above is the detailed content of Introduction to the principles and usage of zuul in SpringCloud. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete