Springcloud Zuul based on consul configuration and detailed

Source: Internet
Author: User

I. Construction PROJECTS

1. Introduction of dependency

        <!--SpringBoot2.0 and above need to introduce this dependency-        <dependency>            <groupid>org.springframework.cloud</ groupid>            <artifactId>spring-cloud-starter-netflix-zuul</artifactId>        </dependency>        <dependency>            <groupId>org.springframework.cloud</groupId>            <artifactId> Spring-cloud-starter-consul-discovery</artifactid>        </dependency>

  2. Create the main class

@SpringBootApplication @enablediscoveryclient@enablezuulproxy@restcontroller  Public class Application {    publicstaticvoid  main (string[] args) {        Springapplication.run (Application. class , args);}    }

  3. Configure Application.properties

ZUUL.ROUTES.API-A.PATH=/API-A/**zuul.routes.api-a.service-id=api-azuul.routes.api-b.path=/ Api-b/**zuul.routes.api-b.service-id=api-b

Here are the api-a and api-b two microservices applications that, when requested Http://localhost:port/api-a/helloWorld, are routed to the/helloworld interface of the API-A service when the request Http://localh The Ost:port/api-b/helloworld is routed to the/helloworld interface that is forwarded to the Api-b service. When the request URL conforms to the configuration rule, it is forwarded to the Service-id corresponding MicroServices application interface.

  4. Configure Request filtering

Springcloud Zuul also has another and core function: request filtering. Zuul allows developers to block and filter requests by defining filters on the API gateway, implementing a simple implementation method that simply inherits the Zuulfilter abstract class and implements the 4 abstract functions it defines to intercept and filter requests.

 Public class Mygatewayfilter extends Zuulfilter {

/*

  pre
  route
  post
  error: Called when an error occurs while processing a request */

Public
    return " Pre " ;
}
@Override Public intFilterorder () {return 0; //Priority is 0, the higher the number, the lower the priority } @Override PublicBoolean shouldfilter () {return true; //Whether to execute the filter, here is true, indicating the need to filter } @Override PublicObject Run () {RequestContext CTX=Requestcontext.getcurrentcontext (); HttpServletRequest Request=ctx.getrequest (); Log.info (String.Format ("%s request to%s", Request.getmethod (), Request.getrequesturl (). toString ()); Object Accesstoken= Request.getparameter ("token"); //Get token parameters if(Accesstoken = =NULL) {Log.warn ("token is empty"); Ctx.setsendzuulresponse (false); //Filter the request and do not route it Ctx.setresponsestatuscode (401); //Return error code ctx.setresponsebody ("token is null!"); //Return error content return NULL; //zuul has not yet processed the return data }
return NULL; }}

  

Once the filter is created, it does not take effect directly, and we also need to create a specific Bean for it to start the filter.

@SpringBootApplication @enablediscoveryclient@enablezuulproxy@restcontroller  Public class lixjapplication {    publicstaticvoid  main (string[] args) {        Springapplication.run (lixjapplication. class , args);    }     @Bean    public  mygatewayfilter mygatewayfilter () {        return  New  mygatewayfilter ();    }}

Two. Detailed routing

  1. Path matching rules  

/api-a/? Can match/api-a/after the path stitching a task character, such as/api-a/a,/api-a/b,/api-a/c

/api-a/* can match/api-a/after the path of any character stitching, such as/api-a/a,/API-A/AAA,/api-a/bbb. But it can't match/api-a/a/b this multilevel directory path

/api-a/** can match/api-a/* contained content and can also match a multi-level directory path such as/api-a/a/b

  2. Route matching Order

With the iteration of the version, we need to do some functional splitting of a service, splitting some of the functionality originally belonging to the Api-a service into another completely new service Api-a-part, and these split external call URL paths would want to conform to the rules/api-a/part/**.

Zuul.routes.api-a.path=/api-a/* * zuul.routes.api-a.service-id=api-a zuul.routes.api-a-part.path=/ api-a/part/** Zuul.routes.api-a-part.service-id=api-a-part

In the source code, the routing rules are saved through Linkedhashmap, that is, the routing rules are kept in order, and the content is loaded by traversing the routing rules in the configuration file, so the root cause of the problem is the reading of the contents of the configuration file. However, the above properties configuration does not guarantee the order of routing rules loading, we need to use the YML file to configure to implement an orderly routing rule.

Zuul:    routes:        API-a-part:            path =/api-a/part/* *            service-id= Api-a-part        api-a:            path=/api-a/**            service-id=api-a        

  3. Local Jump 

Zuul.routes.api-c.path=/api-c/**zuul.routes.api-c.url=forward:/api-c

The above configuration uses a local jump, and when the URL conforms to the/api-c/** rule, it is forwarded to the corresponding interface of its own service by the gateway.

  

Springcloud Zuul based on consul configuration and detailed

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.