Spring Cloud Learning Series fifth "API Gateway service"

Source: Internet
Author: User
Tags set time types of filters

This essay goes on to learn a more important Component API Gateway service in MicroServices. When we finally have to provide external access to the micro-service architecture, we need a unified access portal, to hide our internal service URL details, which is a bit like the concept of the gateway in the LAN, this is the API Gateway Service has emerged. API Gateway is capable of providing the basic functions of request routing, load balancing, checking and filtering, as well as advanced functions such as fuse mechanism of request forwarding, service collection and so on. Supplement usually we can use F5, nginx and other ways to achieve the front request routing and load balancing, but to achieve the function of the F5, Nginx will be powerless, this is the API Gateway service is powerful. In the spring cloud, we can build our API Gateway service with Spring Cloud Zuul, Zuul can be integrated with the spring cloud family of these components, so that the design can better achieve whether it is request routing, load balancing or fusing, Service mechanism.

Then in the API Gateway request routing, filter, service fault tolerance three aspects of learning, API Gateway build jumped over, because it and Eureka is very simple can be set up, you can understand the next.

One, request routing

Service Routing Configuration

Because Zuul integrates with Eureka to know the request address of each service, routing can be configured through zuul.routes.<service-name>=<path> when the access address such as HTTP/ 127.0.0.1:7001/API-A/USER/1, the routing unit will be configured and forwarded to the corresponding service.

URLs that start with the #凡是以/api-a/are forwarded to theapplication with theservice name service-a zuul.routes.service-a=/api-a/**

Default routing Rules

Zuul is not configured to have a default routing rules, you can avoid the trouble of our configuration. By default, the service name is the service that corresponds to the path configuration. Let's say we have a service called service-a, and that Zuul will create the following routing rules by default.

Zuul.routes.service-a=/service-a/**

#如果不希望使用默认路由规则, we can use zuul.ignored-servies=* to cancel the Zuul default route

Custom Routing Rules

If you feel that the default routing rules do not meet your business requirements, you can also define your own routing rules through a custom routing rule, or for example: the service name is SERVICE-A, the default routing rule is/service-a/**, but if you want to change the default routing rule to/service/a/** You can add the Patternserviceroutemapper class in the Startup class and use regular expressions to name the groupings to match the service name and customize your own routing rules, as in the following example, When the service name conforms to the regular expression of the first parameter of the Patternserviceroutemapper constructor (? <part1>^.+)-(? <part2>.+$), and gets the named grouping Part1 and Part2, The second parameter can then be used to define the route. Of course, if a regular expression that does not conform to the first argument goes to the default routing rule.

 PackageCom.pumpkin;ImportOrg.springframework.boot.builder.SpringApplicationBuilder;Importorg.springframework.cloud.client.SpringCloudApplication;ImportOrg.springframework.cloud.netflix.zuul.EnableZuulProxy;ImportOrg.springframework.cloud.netflix.zuul.filters.discovery.PatternServiceRouteMapper;ImportOrg.springframework.context.annotation.Bean, @EnableZuulProxy @springcloudapplication Public classApplication { Public Static voidMain (string[] args) {NewSpringapplicationbuilder (Application.class). Web (true). Run (args); } @Bean Publicpatternserviceroutemapper Serviceroutemapper () {return NewPatternserviceroutemapper ("(? <part1>^.+)-(? <part2>.+$)",                "${part1}/${part2}"); }}

Path matching

When you define a route, you typically use wildcards, and the Zuul wildcard uses the ant style definition, as follows. It is important to note that the routing configuration of Zuul is configured according to the order rather than the longest configuration path match. in other words, when a URL area is configured for routing, and there are multiple routes that can be matched, the following matches are ended once the first route that can be matched is found.

  

  In addition, Zuul also provides an ignore expression for ignoring URL expressions that you do not want to be routed by the API gateway, such as the/hello.do interface of the SERVICE-A service that you do not want to be routed to, and you can add the following configuration.

zuul.ignored-patterns=/**/hello.do/**

Local jump

In the Zuul implementation of the API gateway routing function, also supports the forward form of server-side jump configuration, that is, you can set a routing rule, according to the routing rules will be forwarded to the Zuul gateway itself to handle, of course, when using local jump, Zuul Gateway also has to implement the corresponding interface.

#本地跳转
#当我访问http://127.0.0.1:7001/api-b-url/hello, will be forwarded to Zuul itself to handle Zuul.routes.api-b-url.path=/api-b-url/** zuul.routes.api-b-url.url=forward:/local

Cookie and header information

By default, Zuul will filter out some HTTP request header information when processing a request, and the default sensitive header information is defined by the Zuul.sensitiveheaders parameter, including cookies, Set-cookie, authoriztion three properties, Therefore, the Web project commonly used cookies are not passed by default, in order to solve this problem, there are several configuration methods.

#通过设置全局参数为空覆盖默认值 #zuul.sensitiveheaders=#对指定路由开启自定义敏感头 #zuul.routers. <router>.customsensitiveheaders=true#讲指定路由的敏感头设置为空 #zuul.routers. <router>.sensitiveheaders=

In addition to the cookie problem, there is a redirect issue that needs to be understood. Because Zuul does not properly handle the host in the HTTP request header information, some of the following problems may occur under a redirect scenario: for example, sending a login request to the Zuul gateway, and the backend service returns a 302 redirect response after the login is successful. The host header information for the response may be the IP and port of the specific instance, at which point the browser may see the IP of the instance instead of the IP of the gateway, such as. This problem needs to be solved after the Camden version can be processed by the attribute zuul.add-host-header=true, but based on the current version of this I have not provided a direct solution, You need to refer to the Camden version of the Predecorationfilter filter to handle it yourself.

Second, filter

Zuul filter should be said to be the most important part of Zuul, it mainly provides four types of filters, the four kinds of filter based on the abstract class (Zuulfilter) is the same, but different filters in the Zuul role, the life cycle is not the same, Let's take a look at some important abstract methods of Zuulfilter abstract class.

   #这个属性有四种类型对应不同的过滤器分别是pre, routing, posting, error    publicabstract  Java.lang.String FilterType ();   #决定过滤器执行顺序, the smaller the value the higher the    priority public abstractint  filterorder ();  #判断过滤器是否要执行     boolean  shouldfilter (); #过滤器执行逻辑    Java.lang.Object Run ();

Introducing four types of filters

Through Zuulfilter Introduction Basic understanding of how the filter is used, directly write a class to inherit Zuulfilter, indicating the type of the filter, priority, logic, and then be loaded by spring, then the different types of filter life cycle and role? The following official big picture shows the comparison clearly.

Pre filter: Called before the request is routed, this phase is well known to be suitable for some verification logic

Routing filter: Called when routing a request

Post filter: Called after the Routing and error filters, this type of expiration is typically used to do some processing of the request response results

Error: A call occurred while processing the request

In spring Cloud Zuul is already a batch of default implemented core filters, they will be automatically loaded and enabled at Zuul startup, you can see an interesting path is the error filter in any type of filter exception will be entered, But it will also eventually go into the post filter to return the request to the client.

 

Disable Filters

Sometimes we need to disable the need for some of the default filters or custom filters, so you can zuul the following

#其中 <SimpleClassName> for simple class name,<filtertype> for filter # type Zuul. <simpleclassname>.<filtertype>.disable=trueEg:zuul. AccessFilter.pre.disable=true

Handling Exception Information

This is a common requirement in development, in the <<spring Cloud Micro-service >> a book and the Eternal Super God blog has a more detailed introduction, Skip ~ ~

third, service fault tolerance

Since it is a member of Spring cloud, there is certainly hystrix and ribbon support in terms of service fault tolerance. That is, Zuul inherently has the ability to thread isolation, circuit breakers, client load balancing, but when you set up the route, you need to zuul.routes.service-a=/api-a/** the way the service is routed, otherwise there will be no service fault tolerance. The configuration of the Hystrix and ribbon is the same as the original, briefly introduced.

Hystrix.command. default. execution.isolation.thread.timeoutInMilliseconds--- Set the request time-out period ribbon. ConnectTimeout and Ribbon.readtimeout set time is less than Hystrix.command. default . Execution.isolation.thread.timeoutInMilliseconds when a request to create a connection time-out or a request time-out occurs, the Ribbon retries the routing request, If we do not want this retry mechanism to be available through zuul.retryable=false - global shutdown or zuul.routers. <route>.retryable=False -Specifies that the route is closed

Iv. Summary

API Gateway can be said to be an integral part of the micro-service closed-loop, today the spring Cloud Zuul related content to learn the greatest feeling is that Zuul is actually a "micro-service" feature of a service agent tool, It is this feature that makes it not the same as Nginx and F5 these service proxy tools, to do more things, such as testing, service fault tolerance, processing the request results, and so on, to ensure that the micro-service can be stable operation.

Vi. References

Spring Cloud Micro-service combat-Suphing. This series of studies is based on this book, and the source uses the spring boot and Spring cloud versions to be consistent with it.

Vii. Source Code

Code Cloud Address: [email protected]:p umpkingg/spring-cloud-study.git the code corresponding to this essay is the tag named Blog4 under the master branch

Spring Cloud Learning Series fifth "API Gateway service"

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.