Springcloud Learning-routing Gateway (Zuul)

Source: Internet
Author: User
Tags aws regions

1, Zuul Introduction

1.1. What is Zuul?

Zuul is an API Gateway server for Netflix open source, essentially a Web servlet application.

Zuul provides a framework for dynamic routing, monitoring, resiliency, security and other edge services on cloud platforms. Zuul corresponds to the front door of all requests from the Web site backend of the device and Netflix streaming app.

The main function of Zuul is routing forwarding and filtering. The routing feature is part of the microservices, such as/api/user forwarding to the User Service, and/api/shop forwarding to the shop service. The Zuul default and ribbon combine to achieve load balancing capabilities.

1.2. What Zuul can do

The core of Zuul is a series of filtersthat can be used to mimic the filter of the servlet framework, or AOP.

Zuul can implement the following functions by loading the dynamic filtering mechanism:

    • Verification and security: Identify authentication requirements for a variety of resources and reject requests that do not conform to the requirements.
    • Review and monitoring: track meaningful data and statistical results at the edge to give us accurate production status conclusions.
    • Dynamic routing: Dynamically route requests to different back-end clusters as needed.
    • Stress testing: Gradually increase the load flow to the cluster to calculate performance levels.
    • Load distribution: Allocate the corresponding capacity for each type of load and discard requests that exceed the qualified value.
    • Static response processing: A partial response is created directly at the edge location, preventing it from flowing into the internal cluster.
    • Multi-zone resiliency: Request routing across AWS regions, designed to diversify elb and ensure that edge locations are as close as possible to users.

2. Create Service-zuul Project

  2.1, create Service-zuul project, Pom.xml file as follows

<?XML version= "1.0" encoding= "UTF-8"?><Projectxmlns= "http://maven.apache.org/POM/4.0.0"Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"xsi:schemalocation= "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">    <modelversion>4.0.0</modelversion>    <groupId>Com.lishun</groupId>    <Artifactid>Service-zuul</Artifactid>    <version>0.0.1-snapshot</version>    <Packaging>Jar</Packaging>    <name>Service-zuul</name>    <Description>Demo Project for Spring Boot</Description>    <Parent>        <groupId>Com.lishun</groupId>        <Artifactid>Cloud</Artifactid>        <version>1.0-snapshot</version>        <RelativePath/> <!--Lookup parent from repository -    </Parent>    <Dependencies>        <Dependency>            <groupId>Org.springframework.cloud</groupId>            <Artifactid>Spring-cloud-starter-netflix-zuul</Artifactid>        </Dependency>        <Dependency>            <groupId>Org.springframework.cloud</groupId>            <Artifactid>Spring-cloud-starter-netflix-eureka-client</Artifactid>        </Dependency>        <Dependency>            <groupId>Org.springframework.boot</groupId>            <Artifactid>Spring-boot-starter-web</Artifactid>        </Dependency>    </Dependencies></Project>

2.2, in its entrance Applicaton class plus annotated @enablezuulproxy, open the function of Zuul:

@EnableZuulProxy @enableeurekaclient@springbootapplication  Public class servicezuulapplication {    publicstaticvoid  main (string[] args) {        Springapplication.run (servicezuulapplication. class , args);}    }

2.3, plus the configuration file application.yml plus the following configuration code:

Eureka:  Client:    serviceurl:      defaultzone:http://localhost:8761/eureka/server:  Port: 8769spring:  application:    Name:service-zuulzuul:  routes:    api-a:      path:/api-a/**      Serviceid:service-ribbon    api-b:      path:/api-b/**      serviceid:service-feign

First specify the service registry address is http://localhost:8761/eureka/, the service port is 8769, the service name is Service-zuul;

Requests beginning with/api-a/are forwarded to the Service-ribbon service, and all requests beginning with/api-b/are forwarded to the Service-feign service;

2.4, start 5 services, browser access Http://localhost:8769/api-a/hi?name=lis page display

Hi Lis, I am from port:8762

Browser Access Http://localhost:8769/api-b/hi?name=lis page display

Hi Lis, I am from port:8762

This means that Zuul is acting as a route.

3. Service filtering

 As mentioned earlier, Zuul by loading the dynamic filtering mechanism, not only can realize the routing function, but also can realize verification, inspection, monitoring and other functions.

The following uses the Zuul to implement the security authentication function

  

@Component Public classMyfilterextendsZuulfilter {Private StaticLogger log = Loggerfactory.getlogger (myfilter.class); @Override PublicString FilterType () {return"Pre"; } @Override Public intFilterorder () {return0; } @Override Public BooleanShouldfilter () {return true; } @Override PublicObject Run ()throwszuulexception {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; }}

FilterType: Returns a String representing the type of filter, and defines the filter type for four different lifecycles in Zuul, as follows:

      • Pre: Before routing
      • Routing: The time of routing
      • Post: After routing
      • Error: Sending the wrong call
      • Filterorder: The Order of filtering
      • Shouldfilter: Here can write logical judgments, whether to filter, this article true, filter forever.
      • Run: The specific logic of the filter. Can be complicated, including checking sql,nosql to see if the request has access.

At this time visit: Http://localhost:8769/api-a/hi?name=lis; page display:

Token is empty

Visit http://localhost:8769/api-a/hi?name=lis&token=22; page display:

Hi Lis, I am from port:8762

Springcloud Learning-routing 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.