Play Turn Springcloud (f version) four. Routing Gateway (Zuul)

Source: Internet
Author: User
This post is based on:

play turn Springcloud one. Registration and discovery of services (Eureka)

02) play Turn Springcloud two. Service consumer (1) ribbon+resttemplate

03) Play Turn Springcloud two. Service consumer (2) feign

04) Turn Springcloud three. Circuit breakers (Hystrix) Resttemplate+ribbon and feign two different ways

Four Routing Gateway (Zuul)

In the micro-service architecture, several basic service governance components are needed, including service registration and discovery, service consumption, load balancing, circuit breakers, intelligent routing, configuration management , etc., which are co-organized by these basic components to form a simple microservices system.

in the A common load-balancing approach in Spring Cloud MicroServices is that client requests are first load-balanced (Zuul, Ngnix), then the service Gateway (Zuul cluster), and then to the specific server. , the service is registered to a highly available service registry cluster, all the configuration files of the service are managed by the Configuration service, the configuration files of the configuration service are placed in the git repository , so that developers can change the configuration at any time.

One Z Uul Introduction

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.

Zuul has the following features:

· Authentication

· Insights

· Stress Testing

· Canary Testing

· Dynamic Routing

· Service Migration

· Load Shedding

· Security

· Static Response Handling

· Active/active Traffic Management

Two Configure Routing

Project structure:

in the original project, create a new project. Demo5

dependent on the main project and the required jar Packages:

<Parent>   <groupId>Com.fsdm</groupId>   <Artifactid>Springcloud_test1</Artifactid>   <version>1.0-snapshot</version></Parent><Dependencies>   <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>   <Dependency>      <groupId>Org.springframework.cloud</groupId>      <Artifactid>Spring-cloud-starter-netflix-zuul</Artifactid>   </Dependency></Dependencies>

in its entry Applicaton class plus annotation @enablezuulproxy, the function of Zuul is turned on:

@SpringBootApplication@EnableZuulProxy@EnableEurekaClient @enablediscoveryclientpublic class demo5application {   publicstaticvoid  main (string[] args) {      Springapplication.run (demo5application. class , args);}   }

Annotation parsing:

@EnableZuulProxy

If you use annotations @EnableZuulProxy, in addition to the above filters,Spring Cloud adds the following filters:

1.Pre type filter

Predecorationfilter: The filter determines the address to which the route is routed,based on the provided routelocator , and how to route it. The router can also set up various agent-related headers for back-end requests .

2.Route Type filter

(1) Ribbonroutingfilter: The filter uses the Ribbon,hystrix and pluggable HTTP The client sends the request. serviceId in requestcontext.getcurrentcontext (). Get ("ServiceId") . The filter can use different HTTP clients, such as

Apache HttpClient: Default HTTP client

Squareupokhttpclient v3: If you need to use this client, you need to ensure that the com.squareup.okhttp3 depends on the classpath , and set ribbon.okhttp.enabled = True.

Netflix Ribbon HTTP client: Set ribbon.restclient.enabled = True to enable the http client. It is important to note that the client has some limitations, such as the PATCH method is not supported , and it has a built-in retry mechanism.

(2) Simplehostroutingfilter: The filter sends a request to the specified URL via Apache HttpClient . the URL is in requestcontext.getroutehost () .

YML configuration:

Eureka:  Client:    serviceurl:      Defaultzone: http://localhost:8761/eureka/Server:  Port: 8766Spring:  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 8766, and the service name is Service-zuul;/api-a/ The initial request is forwarded to the Service-ribbon service, and the request beginning with/api-b/is forwarded to the Service-feign service;

Run all five projects:

Open Browser respectively Visit:

HTTP://LOCALHOST:8766/API-A/HI?NAME=FSDM;

HTTP://LOCALHOST:876/API-B/HI?NAME=FSDM;

Browser display:

This means that Zuul is acting as a route.

Three Service Filtering

Project structure:

Zuul is not only a route, but also a filter to do some security verification . Continue to reform the project;

To add a filter class:

@Component Public classMyfilterextendsZuulfilter {/*** FilterType: Returns a String representing the type of filter, defined in the Zuul for four different life cycle filter types, as follows: * PRE: Route before * Routing: time of route * Post: After route * ERROR: Send wrong call*/@Override PublicString FilterType () {return"Pre"; }    //Order of filtering@Override Public intFilterorder () {return0; }    //Here you can write logical judgments, whether to filter, this article true, filter forever. @Override Public BooleanShouldfilter () {return true; }    //the specific logic of the filter. Can be complicated, including checking sql,nosql to see if the request has access. @Override PublicObject Run ()throwszuulexception {System.out.println ("=============================================================="); RequestContext CTX=Requestcontext.getcurrentcontext (); HttpServletRequest Request=ctx.getrequest (); System.out.println (String.Format ("%s >>>%s", Request.getmethod (), Request.getrequesturl (). toString ()); Object Accesstoken= Request.getparameter ("token"); if(Accesstoken = =NULL) {System.out.println ("Token is empty"); Ctx.setsendzuulresponse (false); Ctx.setresponsestatuscode (401); Try{ctx.getresponse (). Getwriter (). Write ("Token is empty"); }Catch(Exception e) {}return NULL; } System.out.println ("OK"); return NULL; }}

visit:http://localhost:8766/api-a/hi?name=fsdm ; Web page display:

visit http://localhost:8766/api-a/hi?name=fsdm&token=22 page display:

Here is a very simple simulation verification, whether or not the token value to determine whether there is permission to access

                            Not finished, to be continued ...

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.