Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to understand Spring Cloud Gateway Service zuul

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces the knowledge of "how to understand Spring Cloud Gateway Service zuul". In the operation of practical cases, many people will encounter such a dilemma. Next, let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

You can see that the service port and registry are configured in the configuration file

Attribute information

In the last article, we talked about how to build a gateway zuul service. The basic forwarding function is realized. In this article we will talk about the use of zuul filters. And the use of three parameters

The sensitiveHeaders attribute keyword declares that the Spring Cloud micro-service playbook means release field. The editor looked up in the official document and found that it ignored the meaning of not letting go. Please note here that practical students who have seen Spring Cloud microservice can confirm it with the example code of the editor.

Ribbon-isolation-strategy

Semaphore mode in this mode, receiving requests and executing downstream depend on completing in the same thread, and there is no performance overhead caused by thread context switching. Default semaphore mode

Thread pool in this mode, user requests are submitted to their respective thread pools for execution, separating the threads executing each downstream service, thus achieving resource isolation. When the thread pool is too late to process and the request queue is full, new requests will fail quickly, preventing dependency problems from spreading.

Isolation mechanism Spring Cloud default isolation mechanism hystrix to do current limiting, fusing, isolation. One is based on semaphores. One is based on thread pool.

Ignored-services

Ignore the specified service

Ignored-patterns

Ignore the specified url path

Ignored-headers

Ignore the specified header header information

SensitiveHeaders

Fields are sensitive and do not want to be passed to downstream microservices. Set empty sensitive fields that do not want to be ignored. All to downstream services.

There is an overlap between ignored-headers and sensitiveHeaders responsibilities above. In fact, they have a relationship. The contents of sensitiveHeaders will eventually be merged into ignored-headers.

Verify that the sensitiveHeaders field is set to ignore X-ABC in the whole area

Consumer Service sensitiveHeaders specifies to ignore XMui ABCMagi Authorization

Service provider forwarding does not make any adjustments to service providers and service consumer services. All create a UrlFilter interceptor. First set up the yml file of zuul.

Zuul: host: # maximum number of connections to the target host. Default is 200 max-total-connections: 500 # initial connections per host The default value is 20 max-per-route-connections: 100 routes: discovery-server: path: / server/** serviceId: cloud-discovery-server client-common: path: / client/** serviceId: cloud-discovery-client sensitiveHeaders: the default Hystrix quarantine mode (ExecutionIsolationStrategy) for all routes is SEMAPHORE. If this isolation mode is preferred, zuul.ribbonIsolationStrategy can be changed to the attribute meaning of THREAD ribbon-isolation-strategy: thread #, * ignore the specific service name in the unspecified service list, ignore the specified service ignored-services: "*" # ignore the specified url path ignored-patterns: # ignore the specified header header information ignored-headers: Authorization # field is sensitive and do not want to be passed to downstream micro-services. Set empty sensitive fields that do not want to be ignored. All are passed to the downstream service sensitive-headers: X-ABC ribbon: eager-load: # to force loading. Lazy loading will occur if it is not set. Spring's first request will be very slow enabled: truepackage com.xian.cloud.filter;import lombok.extern.slf4j.Slf4j;import javax.servlet.*;import javax.servlet.annotation.WebFilter;import javax.servlet.http.HttpServletRequest;import java.io.IOException;import java.util.Enumeration / * @ author xianliru@100tal.com * @ version 1.0 * @ createDate 13:57 on 2019-10-29 * / @ WebFilter (filterName = "test", urlPatterns = "/ *") @ Slf4jpublic class UrlFilter implements Filter {@ Override public void init (FilterConfig filterConfig) throws ServletException {log.warn ("UrlFilter init.") } @ Override public void doFilter (ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {Enumeration attributeNames = servletRequest.getAttributeNames (); HttpServletRequest req = (HttpServletRequest) servletRequest; String requestURI = req.getRequestURI (); String header = req.getHeader ("X-Foo"); String abc = req.getHeader ("X-ABC"); String authorization = req.getHeader ("Authorization"); String tom = req.getParameter ("tom") String mike = req.getParameter ("mike"); log.warn ("filter: request address" + requestURI); log.warn ("uuid: {}", header); log.warn ("abc uuid: {}", abc); log.warn ("authorization: {}", authorization); log.warn ("tom: {}", tom); log.warn ("mike: {}", mike) FilterChain.doFilter (servletRequest, servletResponse);} @ Override public void destroy () {log.warn ("filter destroyed");}}

Add @ ServletComponentScan to the startup class to scan the filter @ WebFilter annotation

Package com.xian.cloud;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.boot.web.servlet.ServletComponentScan;import org.springframework.cloud.client.discovery.EnableDiscoveryClient;/** * @ Author: xlr * @ Date: Created in 2:44 PM 2019-10-27 * / @ EnableDiscoveryClient@SpringBootApplication// New Notes @ ServletComponentScanpublic class DiscoveryServerApplication {public static void main (String [] args) {SpringApplication.run (DiscoveryServerApplication.class, args);}}

Use postman to request the server to print the log

2019-10-30 11 WARN 10 WARN 35.822-[nio-9012-exec-8] com.xian.cloud.filter.UrlFilter: filter: request address / server/hello2019-10-30 11 com.xian.cloud.filter.UrlFilter: request address / WARN 35.826 WARN 48882-[nio-9012-exec-8] com.xian.cloud.filter.UrlFilter: uuid:x-foo2019-10-30 11 Switzerland 1035.826 WARN 48882-[nio] -9012-exec-8] com.xian.cloud.filter.UrlFilter: abc uuid:null2019-10-30 11 abc uuid:null2019 10 WARN 35.827 WARN 48882-[nio-9012-exec-8] com.xian.cloud.filter.UrlFilter: authorization: null2019-10-30 11 11 WARN 10 WARN 35.827-[nio-9012-exec-8] com.xian.cloud.filter.UrlFilter: tom: null2019-10-30 11: 10 WARN 35.828 WARN 48882-[nio-9012-exec-8] com.xian.cloud.filter.UrlFilter: mike: null2019-10-30 11 com.xian.cloud.filter.UrlFilter 10-[nio-9012-exec-8] c.x.cloud.controller.DiscoverCotroller: invoked name = xian age = 20

The global settings of sensitive-headers and ignored-headers (abc and authorization are all filtered out in zuul) take effect.

We request the client service interface again

Take a look at the client print log again.

2019-10-30 11 WARN 1715 05.813 WARN 50223-[nio-9011-exec-3] com.xian.cloud.filter.UrlFilter: filter: request address / client/test2019-10-30 11 WARN 175.813 WARN 50223-[nio-9011-exec-3] com.xian.cloud.filter.UrlFilter: uuid:null2019-10-30 1117 com.xian.cloud.filter.UrlFilter 05.813 WARN 50223-- [nio-9011] -exec-3] com.xian.cloud.filter.UrlFilter: abc uuid:null2019-10-30 1111 WARN 05.813 WARN 50223-[nio-9011-exec-3] com.xian.cloud.filter.UrlFilter: authorization: null2019-10-30 1111V 17Switzerland 05.813 WARN 50223-[nio-9011-exec-3] com.xian.cloud.filter.UrlFilter: tom: null2019-10-30 11:17: 05.813 WARN 50223-[nio-9011-exec-3] com.xian.cloud.filter.UrlFilter: mike: null

Global settings and individual service customization settings all take effect.

Filter

Spring cloud Zuul includes two functions: routing and filtering requests. The routing function is responsible for forwarding the request to the specific micro-service, while the filter is responsible for interfering with the processing of the request, which is the basis for realizing the functions such as permission verification, service aggregation and so on.

In practice, route mapping and request forwarding are done by several different filters. Every http request that enters the zuul goes through a series of filter processing chains to get the request response and return it to the client.

Zuul1.0 has two functions of routing, distribution and filtering of traffic. Routing allows traffic to be distributed to internal micro-service clusters. Filter to modify or personalize the request. Realize authentication, security, monitoring, logging and so on.

During the operation, the traffic request will be forwarded to the corresponding service through a series of filters.

The main FilterType types of zuul routers are divided into four types. A static response StaticResponseFilter

Pre is called before the request is routed. Corresponds to the doFilter method in the Filer of the spring boot project.

Route is used to route to the origin and is called using the http protocol. It is understandable to be responsible for forwarding requests to microservices.

Error error handling, which is called when an error occurs in the processing request

Post is used for post-route filtering and is called after route and error filters

Custom filter

FilterTypeEnum enumerated class

Package com.xian.cloud.enums;import lombok.Getter;/** @ author xianliru@100tal.com * @ version 1.0 * @ createDate, 2019-10-29 13:01 * / @ Getterpublic enum FilterTypeEnum {PRE ("pre", "pre-filtering"), ROUTE ("route", "called on routing request"), POST ("post", "post filter"), ERROR ("error", "post error handling") Private String type; private String desc; FilterTypeEnum (String type,String desc) {this.type = type; this.desc = desc;}}

Filter code writing

Package com.xian.cloud.filter;import com.netflix.zuul.ZuulFilter;import com.netflix.zuul.context.RequestContext;import com.netflix.zuul.exception.ZuulException;import com.xian.cloud.enums.FilterTypeEnum;import lombok.extern.slf4j.Slf4j;import org.apache.commons.lang3.StringUtils;import org.springframework.stereotype.Component;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.util.ArrayList;import java.util.List;import java.util.UUID / * @ author xianliru@100tal.com * @ version 1.0 * @ createDate 12:57 on 2019-10-29 * / @ Component@Slf4jpublic class BannedAccessFilter extends ZuulFilter {/ * the type of router specifies * @ return * / @ Override public String filterType () {return FilterTypeEnum.PRE.getType ();} / * the smaller the execution order. The higher the execution order, the higher the * @ return * / @ Override public int filterOrder () {return 0;} / * returns a Boolean value to determine whether the filter is to be executed. We can use this method to specify the valid range of the filter. * @ return * / @ Override public boolean shouldFilter () {RequestContext context = RequestContext.getCurrentContext (); HttpServletRequest request = context.getRequest (); String requestURI = request.getRequestURI (); if (StringUtils.isNotBlank (requestURI) & & (requestURI.contains ("client") | | requestURI.contains ("server")) {return true;} return false } / * Core business processing * @ return * @ throws ZuulException * / @ Override public Object run () throws ZuulException {RequestContext context = RequestContext.getCurrentContext (); HttpServletResponse servletResponse = context.getResponse (); String uuid = UUID.randomUUID (). ToString (); / / override the X-Foo X-ABC value context.addZuulRequestHeader ("X-Foo", uuid) Context.addZuulRequestHeader ("X-ABC", uuid); log.info ("X-Foo: {}", uuid); return null;}}

The run method is the core business processing method postman request http://127.0.0.1:9083/server/server/hello?name=1111 carries the previously set header parameter

The server prints logs

2019-10-30 14 WARN 444.841 WARN 48882-[nio-9012-exec-9] com.xian.cloud.filter.UrlFilter: filter: request address / server/hello2019-10-30 14 com.xian.cloud.filter.UrlFilter 44 server/hello2019 44.842 WARN 48882-[nio-9012-exec-9] com.xian.cloud.filter.UrlFilter: uuid:a65b2244-e9a5-456d-968f-eaaba45b6f492019-10-30 14V 4440 WARN 48882 -[nio-9012-exec-9] com.xian.cloud.filter.UrlFilter: abc uuid:null2019-10-30 14 WARN 44.842 WARN 48882-[nio-9012-exec-9] com.xian.cloud.filter.UrlFilter: authorization: null2019-10-30 14 WARN 44.842 WARN 48882-[nio-9012-exec-9] com.xian.cloud.filter.UrlFilter: tom: null2019 -10-30 14 com.xian.cloud.filter.UrlFilter 444.842 WARN 48882-[nio-9012-exec-9] com.xian.cloud.filter.UrlFilter: mike: null2019-10-30 14V 44.844 INFO 48882-[nio-9012-exec-9] c.x.cloud.controller.DiscoverCotroller: invoked name = 1111 age = 20

You can see that the X-Foo value set by postman is overridden by the BannedAccessFilter run method business.

All the intercepted requests modify the parameters here. Here is a separate introduction to the RequestContext class.

Official document description

To pass information between filters, Zuul uses a RequestContext. Its data is held in a ThreadLocal specific toeach request. Information about where to route requests, errors and the actual HttpServletRequest andHttpServletResponse are stored there. The RequestContext extends ConcurrentHashMap, so anything can bestored in the context. FilterConstants contains the keys that are used by the filters installed by Spring CloudNetflix (more on these later).

To request to pass information between filters, Zuul uses RequestContext. Its data is carried out according to the ThreadLocal of each request. Routing information about routing requests, errors, and actual HttpServletRequest and HttpServletResponse. RequestContext extends ConcurrentHashMap, so anything can be stored in context.

ThreadLocal ensures that requests and requests are independent and do not affect each other. Extended ConcurrentHashMap ensures the security of concurrent operations of internal filters.

The particularity of RequestContext. You need to create a separate filter to demonstrate the use of RequestContext

The points to be noted are described in the code comments. Please customize your filter according to your business scenario.

Package com.xian.cloud.filter;import com.alibaba.fastjson.JSONObject;import com.netflix.zuul.ZuulFilter;import com.netflix.zuul.context.RequestContext;import com.netflix.zuul.exception.ZuulException;import com.netflix.zuul.http.HttpServletRequestWrapper;import com.netflix.zuul.http.ServletInputStreamWrapper;import com.xian.cloud.enums.FilterTypeEnum;import lombok.extern.slf4j.Slf4j;import org.apache.commons.lang3.StringUtils;import org.springframework.stereotype.Component;import org.springframework.util.StreamUtils;import javax.servlet.ServletInputStream Import javax.servlet.http.HttpServletRequest;import java.io.IOException;import java.io.InputStream;import java.nio.charset.Charset;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;/** @ author xianliru@100tal.com * @ version 1.0 * @ createDate 16:07 on 2019-10-29 * / @ Component@Slf4jpublic class UpdateParamsFilter extends ZuulFilter {@ Override public String filterType () {return FilterTypeEnum.PRE.getType () } @ Override public int filterOrder () {return 1;} @ Override public boolean shouldFilter () {return true;} @ Override public Object run () throws ZuulException {/ / get request RequestContext ctx = RequestContext.getCurrentContext (); HttpServletRequest request = ctx.getRequest (); / / get the request parameter name String name = "" Try {/ / request method String method = request.getMethod (); log.info (String.format ("% s > >% s", method, request.getRequestURL (). ToString ()); / / get the requested input stream InputStream in = request.getInputStream (); String body = StreamUtils.copyToString (in, Charset.forName ("UTF-8")) / / initialize empty body to empty json if (StringUtils.isBlank (body)) {body = "{}";} log.info ("body" + body); / / convert to json JSONObject json = JSONObject.parseObject (body) / / for key steps, be sure to get before you can get the value requestQueryParams if ("GET" .equals (method)) {request.getParameterMap (); Map requestQueryParams = ctx.getRequestQueryParams (); if (requestQueryParams = = null) {requestQueryParams = new HashMap () } / / TODO write business code List arrayList = new ArrayList (); arrayList.add ("hello mike"); / / requestQueryParams.put ("mike", arrayList); ctx.setRequestQueryParams (requestQueryParams) } / / post and put need to rewrite HttpServletRequestWrapper if ("POST" .equals (method) | | "PUT" .equals (method)) {/ / TODO modify or add content json.put ("tom", "hello tom"); String newBody = json.toString (); final byte [] reqBodyBytes = newBody.getBytes () / / rewrite the HttpServletRequestWrapper ctx.setRequest of the context (new HttpServletRequestWrapper (request) {@ Override public ServletInputStream getInputStream () throws IOException {return new ServletInputStreamWrapper (reqBodyBytes)) } @ Override public int getContentLength () {return reqBodyBytes.length;} @ Override public long getContentLengthLong () {return reqBodyBytes.length }});}} catch (IOException e) {e.printStackTrace ();} return null;}} "how to understand the Spring Cloud Gateway Service zuul" ends here. Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report