Springcloud series eight: Zuul routing access (basic usage of Zuul, Zuul routing function, Zuul filtering access, Zuul service demotion)

Source: Internet
Author: User
Tags base64

1. Concept: Zuul Routing Access

2. Specific content

All microservices have been found through Eureka, but in many of the developments in order to standardize the use of microservices, there is a routing control component: Zuul, which means that Zuul acts as a proxy layer in the middle.

2.1, the basic use of Zuul

The use of Zuul will access the non-secure authentication of the micro-service information, such as: The company information is a non-security authentication of micro-services;

1, in order to highlight the function of Zuul, establish a new host mapping:

127.0.0.1 gateway-9501.com

In the future, all microservices access is no longer processed directly, but is zuul through a jump to get

2, the establishment of a new module: microcloud-zuul-gateway-9501;

3, "microcloud-zuul-gateway-9501" Modify the Pom.xml file, append Zuul dependent package:

· Note: The Zuul service will eventually be registered in the Eureka, then it must be configured well;

        <dependency>            <groupId>org.springframework.cloud</groupId>            <artifactId> spring-cloud-starter-zuul</artifactid>        </dependency>        <dependency>            <groupid >org.springframework.cloud</groupId>            <artifactid>spring-cloud-starter-eureka</artifactid >        </dependency>

4, "microcloud-zuul-gateway-9501" Modify the application.yml configuration file:

Server:  Port:9501eureka:  client: # Configuration for Eureka registration    Service-url:      defaultzone:http://edmin:[email Protected]:7001/eureka,http://edmin:[email Protected]:7002/eureka,http://edmin:[email Protected]:7003/eureka  instance:    Lease-renewal-interval-in-seconds:2 # Set the heartbeat time interval (default is 30 seconds)    Lease-expiration-duration-in-seconds:5 # If you now exceed the 5-second interval (default is 90 seconds)    instance-id:gateway-9501.com  # Displays the host name in the information list    prefer-ip-address:true     # Access path changed to IP address info:  app.name:study-microcloud  company.name: www.study.cn  Build.artifactid: $project. artifactid$  build.version: $project. Verson$spring:  Application:    Name:microcloud-zuul-gateway

5. "MICROCLOUD-ZUUL-GATEWAY-9501" creates the main class that the program starts:

Package Cn.study.microcloud;import Org.springframework.boot.springapplication;import Org.springframework.boot.autoconfigure.springbootapplication;import Org.springframework.cloud.netflix.zuul.EnableZuulProxy, @SpringBootApplication @enablezuulproxypublic class Zuul_ 9501_startspringcloudapplication {public    static void Main (string[] args) {        Springapplication.run (zuul_9501_ Startspringcloudapplication.class, args);}    }

You can see that "microcloud-zuul-gateway-9501" is already registered in Eureka.

6, access to the company's micro-service information:

· Original access path: Http://company-8101.com:8101/company/get/hello;

· Zuul proxy access: Http://gateway-9501.com:9501/microcloud-provider-company/company/get/hello;

Only company is now using the Zuul agent because Security authentication on dept is not accessible.

2.2. Zuul Routing function

After the whole Zuul run you will find that Zuul is implemented as an agent function, then there is a problem now, for example: Take the path of the previous access as an example:

Http://gateway-9501.com:9501/microcloud-provider-company/company/get/hello

You must know the name of the application at this point, but if you do not know the name is definitely inaccessible, but if you let the user know the name, then using Zuul will have no practical meaning, directly called. And Zuul's main function is the agent, then the function of the agent is not to let the user see the real operation, so in the actual use of the need to set up some routing rules for Zuul.

1, "microcloud-zuul-gateway-9501" for the specified application set the path, modify the APPLICATION.YML configuration file:

Zuul:  routes:     

The "Microcloud-provider-company" name can be accessed by "/company-proxy" at this point.

Http://gateway-9501.com:9501/company-proxy/company/get/hello

But now there is a real problem, although routing access support is now enabled, but access is still supported through the application name:

Http://gateway-9501.com:9501/microcloud-provider-company/company/get/hello

2, "microcloud-zuul-gateway-9501" Modify the Application.yml profile Ignore app name access:

· Ignore "microcloud-provider-company" application name;

Zuul:  ignored-services:    microcloud-provider-company  routes:     

This time can be used for proxy security, but if you have a system of hundreds of microservices, if the configuration as described above will be very troublesome, so the simplest way is to use a wildcard "*" mode to complete:

Zuul:  ignored-services:    "*"  routes:     microcloud-provider-company:/company-proxy/**

It now means that all information access to the service name in the Eureka is ignored, and all accesses need to be configured with a mapping path pattern to complete.

3, "microcloud-zuul-gateway-9501" in addition to the above model for service definition, in the Zuul can also be used in the following ways to deal with:

Zuul:   ignored-services:    "*"  routes:   mycompany.path:/company-proxy/**   Mycompany.serviceid:microcloud-provider-company

The "MyCompany" that appears in the code is a logical name that is the primary function of binding path to serviceId.

4, "microcloud-zuul-gateway-9501" If you do not want to access through Eureka now, you can also connect directly to the address of the company micro-service

Zuul:   ignored-services:    "*"   routes:    company.path:/company-proxy/**    company.url:http:// Company-8101.com:8101/company

At this point in the address because there is already a "company" prefix, so the access address is:

Http://gateway-9501.com:9501/company-proxy/get/hello

However, this type of pattern processing is not recommended for practical development because all services that bind directly to the specified service provider's address are not convenient for load-balanced configuration processing and are not Eureka to manage all microservices.

5, "microcloud-zuul-gateway-9501" set the common prefix:

Zuul:  prefix:/study-proxy  ignored-services:    "*"  routes:     microcloud-provider-company:/ company-proxy/**

Once there is a prefix definition, a prefix name must be appended to the access of all microservices:

Http://gateway-9501.com:9501/study-proxy/company-proxy/company/get/hello

The above address:

· "/study-proxy": the prefix of the entire zuul;

· "/company-proxy": is the mapping path defined in the Zuul;

· "/company/get/hello": is the operation path provided by the micro service provider.

2.3, Zuul filter access

For the Zuul function is essentially a proxy operation, but in the actual use, all the microservices must have their own authentication information, then in such a state, if you are currently acting micro-services have authentication information, then must be in their access before the authentication of the head operation, Such a feature would need to be done through the Zuul filtering operation.

1, "microcloud-zuul-gateway-9501" Modify the APPLICATION.YML configuration, this configuration to append Dept Micro-Service agent;

Zuul:  prefix:/study-proxy  ignored-services:    "*"  routes:     microcloud-provider-company:/ company-proxy/**     

The access path at this time: Http://studyjava:[email protected]:9501/study-proxy/dept-proxy/dept/get/1; Now the password is only set to Zuul, and Zuul It is not possible to pass the certified information to the departmental micro-service.

2, "microcloud-zuul-gateway-9501" additional filtering processing operation:

Package Cn.study.microcloud.filter;import Java.nio.charset.charset;import Java.util.base64;import Com.netflix.zuul.zuulfilter;import Com.netflix.zuul.context.requestcontext;public class AuthorizedRequestFilter Extends Zuulfilter {//For authorized access processing @Override public Object run () {///represents the specific filter execution action RequestContext CurrentC Ontext = Requestcontext.getcurrentcontext (); Gets the context of the current request String auth = "Studyjava:hello"; The original information of the authentication byte[] Encodedauth = Base64.getencoder (). Encode (Auth.getbytes (Charset.forname ("Us-ascii" ))); Perform an encrypted processing//When authorizing the configuration of the header information content the encrypted information must have a space between the "basic" string authheader = "Basic" + new string (Encodedaut        h);        Currentcontext.addzuulrequestheader ("Authorization", Authheader);    return null;    } @Override public Boolean shouldfilter () {//whether the filter is to execute return true;    } @Override public int filterorder () {return 0; Set priority, the higher the number, the lower the priority} @Override public String FiltertYpe () {///Zuul filter can be set at the time of the filter execution location, then there are several types://1, Pre: Before the request is issued to filter, if you want to access, you must set the header information//2, Route:    Called at the time of the routing request;//3, post: Called when sending request information after routing,//4, Error: Call return "pre" after a fault has occurred; }}

3, "microcloud-zuul-gateway-9501" to establish a configuration program class as the authentication request configuration Bean.

Package Cn.study.microcloud.config;import Org.springframework.context.annotation.bean;import Org.springframework.context.annotation.configuration;import Cn.study.microcloud.filter.AuthorizedRequestFilter; @Configurationpublic class Zuulconfig {    @Bean public    authorizedrequestfilter Getauthorizedrequestfilter () {        return new Authorizedrequestfilter ();}    }

Then this time it means that your current program can access all encrypted microservices directly using Zuul's proxy.

4, "microcloud-zuul-gateway-9501" considering Zuul also need to carry out secure access, so should modify the Pom.xml configuration file in the project, append Spring secure access configuration processing operation:

        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId> Spring-boot-starter-security</artifactid>        </dependency>  

5, "microcloud-zuul-gateway-9501" Modify the application.yml configuration file, the best user information configuration:

Security:  Basic:    enabled:true  User:    name:zdmin    Password:studyjava

Then now that the Zuul agent on the authentication information, the address must be accessed to add Zuul authentication operation:

Http://zdmin:[email PROTECTED]:9501/STUDY-PROXY/DEPT-PROXY/DEPT/GET/1

6, "Microcloud-service" now all the services to be through the Zuul agent to operate the configuration of the agent if you want to access through feign, then in the writing of feign must set the proxy service name;

Package Cn.study.service;import Java.util.list;import Org.springframework.cloud.netflix.feign.feignclient;import Org.springframework.web.bind.annotation.pathvariable;import Org.springframework.web.bind.annotation.requestmapping;import Org.springframework.web.bind.annotation.requestmethod;import Cn.study.commons.config.feignclientconfig;import Cn.study.service.fallback.ideptclientservicefallbackfactory;import cn.study.vo.Dept; @FeignClient (value = " Microcloud-zuul-gateway ", configuration = feignclientconfig.class, Fallbackfactory = Ideptclientservicefallbackfactory.class) public interface Ideptclientservice {@RequestMapping (method =    Requestmethod.get, value = "/study-proxy/dept-proxy/dept/get/{id}") Public dept GET (@PathVariable ("id") long ID); @RequestMapping (method = requestmethod.get, value = "/study-proxy/dept-proxy/dept/list") Public list<dept> list (    ); @RequestMapping (method = requestmethod.post, value = "/study-proxy/dept-proxy/dept/add") Public boolean Add (Dept Dept);} 

7, "Microcloud-service" Modify the configuration class of the service, test access should be Zuul address:

Package Cn.study.commons.config;import Org.springframework.context.annotation.bean;import Org.springframework.context.annotation.configuration;import feign. Logger;import feign.auth.BasicAuthRequestInterceptor; @Configurationpublic class Feignclientconfig {    @Bean    Public Logger.level Getfeignloggerlevel () {        return feign. Logger.Level.FULL;    }    @Bean public    basicauthrequestinterceptor getbasicauthrequestinterceptor () {        return new Basicauthrequestinterceptor ("Zdmin", "Studyjava");}    }

8, "microcloud-zuul-gateway-9501" by default, as long as the filter is configured, you can do a normal start, if now some filters suddenly do not want it to use, you can also modify the APPLICATION.YML configuration file to disable it:

Zuul:  authorizedrequestfilter:     pre:       disable:true

This means that the "Authorizedrequestfilter" filter will be banned. If more than one filtering service appears later, you can enable and disable the filtering through the configuration file.

2.4, Zuul service downgrade

Zuul is a proxy service, then if the service is suddenly broken down, then this time Zuul will show the error message. For example: Now stop the microservices on the "dept-8001:8001" port.

If the program is not available now, the Zuul agent executes with a timeout message. But remember, because now the client has been provided with feign in the service degraded configuration support, so the client does not have any problems, the problem only appears on the proxy side. However, for a well-zuul agent should be better to implement service demotion processing operations, so if necessary, you can also be in the Zuul service downgrade configuration.

1, "microcloud-zuul-gateway-9501" to establish a Fallback fallback processing class.

Package Cn.study.microcloud.fallback;import Java.io.bytearrayinputstream;import Java.io.ioexception;import Java.io.inputstream;import Org.springframework.cloud.netflix.zuul.filters.route.zuulfallbackprovider;import Org.springframework.http.httpheaders;import Org.springframework.http.httpstatus;import Org.springframework.http.client.clienthttpresponse;import org.springframework.stereotype.component;@        Componentpublic class Deptproviderfallback implements Zuulfallbackprovider {@Override public String Getroute () {    return "Microcloud-provider-dept";             Set the failed route for processing} @Override public Clienthttpresponse fallbackresponse () {return new Clienthttpresponse () { @Override public InputStream GetBody () throws IOException {return new Bytearrayinpu                                TStream ("{\" deptno\ ": 777777,\" dname\ ": \" "ERROR" zuul-fallback\ ", \" loc\ ": \" Gateway client provides \ "}"    . GetBytes ());      Data content returned after a service invocation error occurs      } @Override Public Httpheaders getheaders () {httpheaders headers = new Httphea                DERs (); Headers.set ("Content-type", "text/html;                Charset=utf-8 ");            return headers; } @Override Public Httpstatus Getstatuscode () throws IOException {return httpstatus.            Bad_request; } @Override public int getrawstatuscode () throws IOException {return Httpstatus.bad_            Request.value (); } @Override Public String Getstatustext () throws IOException {return Httpstatus.bad_            Request.getreasonphrase ();    } @Override public void Close () {}}; }}

2, "microcloud-zuul-gateway-9501" direct access to the address:

Http://zdmin:[email PROTECTED]:9501/STUDY-PROXY/DEPT-PROXY/DEPT/GET/1

Since you are returning the wrong code at this point, the client receives this code and considers the server side dead.

Springcloud series eight: Zuul routing access (basic usage of Zuul, Zuul routing function, Zuul filtering access, Zuul service demotion)

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.