Springcloud Practice (ii) API Gateway: Zuul

Source: Internet
Author: User
Tags types of filters haproxy

What is Zuul?
    • Front door. API Gateway.zuul is a JVM based router and server side load balancer by Netflix.
    • Entrance to all requests.
    • As an edge service application, Zuul are built to enable dynamic routing, monitoring, resiliency and security. As a boundary application service, Zuul can realize dynamic routing , monitoring, elasticity and security.
    • Written in groovy.

Netflix uses Zuul for the following:

Authentication 认证Insights 洞察力Stress Testing 压力测试Canary Testing 金丝雀测试Dynamic Routing 动态路由Service Migration 服务迁移Load Shedding 减载Security 安全Static Response handling 静态响应处理Active/Active traffic management

If you want to design a gateway later, you can follow the above's really into design.

Precautions for use
    1. If you need your routes to has their order preserved you need to use a YAML file as the ordering would b E lost using a properties file. If you want to follow the routing rules in writing order, you must use a Yaml file and you cannot use the properties
Embedded Zuul Reverse Proxy

Use proxies to facilitate front-end invocation of backend services, avoid cors (cross-domain resource access) and permissions issues,

    • @EnableZuulProxy
    • The proxy uses Ribbon to locate an instance to forward to via discovery, and all requests is executed in a hystrix comman D, so failures would show up in Hystrix metrics, and once the circuit is open the proxy would not try to contact the service The agent invokes the service through the service discovery and locates the instance through the Ribbon, and all requests are executed through the Hystrix command pattern. The failure information will be collected in the Hystrix indicator system, the agent will not be able to access the service once it enters the fuse mode.
    • At a minimum, you need to integrate discovery client such as Eureka
Zuul Http Client

The default HTTP client used by Zuul are now backed by the Apache HTTP client instead of the deprecated Ribbon restclient.

Apache client is now used by default.

Cookies and Sensitive Headers

Sensitive to cookies and headers, which means that headers rules can be developed to filter requests. This feature is available on Spring Cloud Netflix 1.1 or later.

 zuul:  routes:    users:      path: /myusers/**      sensitiveHeaders: Cookie,Set-Cookie,Authorization  # blacklist,如果不过滤,则须显式设为空。      url: https://downstream      set globally by setting zuul.sensitiveHeaders            
Strangulation Patterns and Local forwards

How do I apply the old version to the new version?

    • Kill mode (the way it slowly chokes): Part calls the old app, part calls the new app.
    • Hystrix also provides the ability to control the switching of new and old applications
Uploading Files through Zuul

Small files can be passed Zuul proxy, large files through Spring dispatcherservlet.

Query String Encoding

The result can be different than the original input if it is encoded using Javascript ' s encodeuricomponent () met Hod for example. While this causes no issues on the most cases, some Web servers can is picky with the encoding of complex query string.

zuul:  forceOriginalQueryStringEncoding: true

Note: This special flag for works with simplehostroutingfilter and loose the ability T o easily override query parameters with Requestcontext.getcurrentcontext (). Setrequestqueryparams ( Someoverriddenparameters) Since the query string is today fetched directly on the original httpservletrequest.

Disable Zuul Filters

Many filters are used by default and can be disabled by the following way

Set Zuul.

zuul.SendResponseFilter.post.disable=true
Zuul Timeouts
    • ==zuul when using service discovery and routing, you need to configure the timeout parameters as follows: = =
    • If Zuul is using the service discovery than you need to configure these timeouts via Ribbon properties, Ribbon. ReadTimeout and ribbon. Sockettimeout.

    • If you have configured Zuul routes by specifying URLs than you'll need to use Zuul.host.connect-timeout-mil Lis and zuul.host.socket-timeout-millis.
Rewriting Location Header

If Zuul is fronting a Web application then there could be a need to re-write the location header when the Web application re Directs through a HTTP status code of 3XX. = = when redirected through 3XX, the header needs to be rewritten, otherwise it will redirect to the Web URL instead of the Zuul URL. ==

overriding filter

import org.springframework.cloud.netflix.zuul.filters.post.LocationRewriteFilter;...@Configuration@EnableZuulProxypublic class ZuulConfig {    @Bean    public LocationRewriteFilter locationRewriteFilter() {        return new LocationRewriteFilter();    }}

==note==: Not necessarily in all cases, in case you are redirecting to an external URL.

Zuul Developer guidethe Zuul Servlet

Zuul is implemented as a ==servlet==. For the general cases, Zuul are ==embedded into the Spring Dispatch mechanism==. This allows Spring MVCto is in control of the routing.
Zuul is a request-forwarding mechanism that Servlet.zuul embeds springd so that spring MVC controls routing.

Zuul generally configures cache requests when large files are uploaded with exceptions.

by Default:/zuul. Zuul.servlet-path

Zuul RequestContext

RequestContext

    • Request data is saved in threadlocal, information about where to route requests, errors and the actual httpservletrequest and Httpservletres Ponse is stored there.
    • RequestContext inherited Concurrenthashmap.
@EnableZuulProxy vs. @EnableZuulServer

@EnableZuulProxy > @EnableZuulServer, more routing capabilities. The additional filters in the "proxy" Enable routing functionality.

Filters

How to Write a Route Filter

Extends Zuulfilter inherits the following three types of filters:

    • Pre Filter
    • Route Filter
    • Post Fitler
    • In run (), modify the request, okhttpclient, and response.
How Zuul Errors work

The Senderrorfilter is only run if requestcontext.getthrowable () is not null.

It then sets specific javax.servlet.error.* attributes on the request and forwards the request to the Spring Boot error PA Ge. How do I set this property?
How do AJAX requests work?

Zuul Eager Application Context Loading

Ribbon clients is by default lazily loaded to Spring Cloud on first call. Ribbon clients defaults to lazy loading

Modify the configuration so that it loads when the app starts:

zuul:  ribbon:    eager-load:      enabled: true
Practice the use of URL mapping to implement ZULL forwarding has limitations

Stripprefix default is True. This means, all calls such as "/myusers/101" would be a forwarded to "/101" on the "users" service.

spring.application.name=gateway-service-zuulserver.port=8888#这里的配置表示,访问/it/** 直接重定向到http://www.ityouknow.com/**zuul.routes.baidu.path=/it/**zuul.routes.baidu.url=http://www.ityouknow.com/
Forward via Serviceid (i.e. application name)
zuul:  routes:    producer:      path: /wifi/**      serviceId: wifi-service  strip-prefix: true
Zuul high-availability parameter optimization
    1. Configure request retry for spring Cloud ribbon
zuul.host.connect-timeout-millis zuul.host.socket-timeout-milliszuul.eureka.[service id].semaphore.maxSemaphores: 128spring.cloud.loadbalancer.retry.enabled=truehystrix.command.default.execution.isolation.thread.timeoutInMilliseconds=10000hello-service.ribbon.ConnectTimeout=250hello-service.ribbon.ReadTimeout=1000
Zuul Existing problems

In practice, we will find that there are many problems in using Zuul directly, including:

    • Performance issues: When there are a large number of requests time-out will cause Zuul blocking, currently only through the scale-out Zuul instances to achieve high concurrency support;

    • WebSocket support issues: Zuul does not directly provide support for websocket, need to add additional filters to achieve websocket support;

    • The request rate throttling feature is missing and a third-party jar package is available: Zuul
    • Performance Problem Solution: Cluster, highly available Zuul is just a stateless service with an HTTP endpoint, hence, we can have as many Zuul instances as we nee D.
    • Zuul multiple nodes are started and can be used as services to register on Eureka.

High availability when client was not a Eureka client. The Zuul instances, in this case, 'll be running behind a load balancer such as HAProxy, or a hardware load balancer like NetScaler:

High-availability Load balancing selection Haproxy vs Nginx

Choose Haproxy for the following reasons:

    • Choose from the positioning, haproxy components function single, only to do lb; Nginx focuses on Web servers, replacing Apache with the role of LB
    • Haproxy heartbeat detection, Nginx needs to integrate with third-party plugins
    • Haproxy has a monitoring page
    • Haproxy load Balancing algorithm is more and better.
    • Support for Virtual hosts

If you are worried about lb single point problem, you can use Keepalived+haproxy.

After a certain degree of website concurrency, in order to improve stability and forwarding efficiency, can use LVS, after all, LVs than nginx/haproxy to more stable, more efficient forwarding. However, the maintenance of LVS will be more demanding for maintenance personnel, and the cost of input is also greater.

Prospect

Zuul has been open source for several years, and now has a new open source Project Spring Cloud Gateway, just open source soon, not yet mature. From its published features, the integration of service discovery, circuit breakers, current limiting and other functions.

Spring Cloud Gateway Features:

    • Built on Spring Framework 5, Project Reactor and Spring Boot 2.0
    • Able to match routes on any request attribute.
    • Predicates and filters is specific to routes.
    • Hystrix Circuit Breaker integration.
    • Spring Cloud discoveryclient Integration
    • Easy to write predicates and Filters
    • Request Rate Limiting
    • Path rewriting
Reference documents
    1. Zull Wiki
    2. Spring-cloud-netflix Official Website Brochure
    3. Springcloud (10): Service Gateway Zuul Primary----Environment Construction Primer Reference
    4. Zuul High-availability
    5. API Gateway (Gateway) Those things
    6. Zuul parameter Tuning
    7. Zuul for rate limit

Tips: This article belongs to their own study and practice of the process of recording, many pictures and text are pasted from the online article, no reference please forgive! If you have any questions please leave a message or e-mail notification, I will promptly reply.

Springcloud Practice (ii) API Gateway: Zuul

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.