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

Example Analysis of Service Gateway Spring Cloud Zuul

2025-01-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly shows you the "sample Analysis of Service Gateway Spring Cloud Zuul", which is easy to understand and clear. I hope it can help you solve your doubts. Let me lead you to study and study the article "sample Analysis of Service Gateway Spring Cloud Zuul".

A brief introduction to Zuul

As the gateway component of micro-service system, Zuul is used to build Border Service (Edge Service), which is dedicated to dynamic routing, filtering, monitoring, self-scaling and security. It plays an important role in the micro-service architecture, mainly reflected in the following six aspects:

The combination of Zull, Ribbon and Eureka can realize intelligent routing and load balancing. Zull can distribute requests to different instances according to a certain policy.

As a boundary service, the gateway aggregates the API interfaces of internal services and uniformly exposes the interfaces. Protect the API interface of the internal service from divulging sensitive information by external invocation

The gateway can authenticate the user's identity rights to prevent illegal requests for API interfaces.

The gateway can realize the monitoring function, real-time log output and record the request.

The gateway can be used to monitor traffic and downgrade the service in the case of high traffic.

The API interface is separated from the internal service for easy testing

Second, request routing

The rules for implementing routing using Spring Cloud Zuul are very simple. There are two kinds of routing methods: traditional routing and service-oriented routing.

2.1 traditional routin

Let's take a look at the following configuration:

Zuul.routes.holiday.path=/holiday/**zuul.routes.holiday.url= http://localhosst:8080/

The rule configuration indicates that all accesses that conform to the / holiday/** rule will be routed and forwarded to the http://localhosst:8080/ address, for example, when we visit the http://localhost:5555/holiday/getAllDays,API gateway, the request will be forwarded to the microservice interface provided by http://localhost:8080/holiday/getAllDays. Where holiday is the name of the microservice, which can be defined arbitrarily, but the route names of a set of path and url mappings must be the same, as does the following service-oriented routing.

2.2 Service-oriented routing

Spring Cloud Zuul and Spring Cloud Eureka can be seamlessly docked to achieve service-oriented routing. We map the routed path to specific services, while the specific url is automatically maintained by Eureka's service discovery mechanism. The specific configuration is as follows (for other configurations, please see the actual combat below):

Zuul.routes.holiday.path=/holiday/**zuul.routes.holiday.service-id=holiday

Through the above configuration, we do not need to maintain the location of the specific instance, but the maintenance work is very simple. In addition, service-oriented routing implements load balancing by default, while traditional routes also need to manually add the locations of all instances.

III. Routing rules

Spring Cloud Zuul provides a default routing rule, which we can also modify.

3.1 default routing rules

When Zull is used with Eureka, Zull configures a routing rule by default, and the path of these default rules uses the service name configured by service-id as the prefix for the request. For example, there is a holiday service, and its default rules are as follows

Zuul.routes.holiday.path=/holiday/**zuul.routes.holiday.service-id=holiday

By default, all services on Eureka are automatically created by Zuul to create mapping relationships for routing, which makes some services that we do not want to open to the outside world can also be accessed externally. At this point, we can configure the zuul.ignored-services parameter to set a service name matching expression to determine. If the service name matches the expression, then Zull will skip the service and do not create routing rules for it. For example, zuul.ignored-services=* means that routing rules are not automatically created for all services, so we need to configure routing rules for each service.

3.2 Custom routing rules

There is a scenario where there are different versions of the service due to the expansion of the business and the upgrade of the version. For example, we have such names: holiday-v1 and holiday-v2. By default, the routing expression automatically created by Zuul for the service will be prefixed with the service name, and two paths / holiday-v1,/holiday-v2 will be generated for holiday-v1 to do mapping, but the resulting expression rule is relatively simple, which is not conducive to the management of path rules.

In general, for the above case, we want the generated path to be / v1Universe holidayrecoveryhand v2Universe. We can implement this by customizing routing rules, as follows:

@ Beanpublic PatternServiceRouteMapper serviceRouteMapper () {return new PatternServiceRouteMapper ("(? ^. +)-(? v. name $)", "${version} / ${name}");}

The PatternServiceRouteMapper object allows developers to customize generation relationships that serve route maps through regular expressions.

IV. Zuul filter

Zull has a request filtering function, and its filter can execute a series of filters during the initiation of the Http request and the response return.

Zuul package expands the following four filters:

PRE: this type of filters is executed before the Request routing reaches the source web-service. You can do some permission authentication, log recording, or add some additional attributes to Request for subsequent filter use.

ROUTING: this type of filters is used to bring Request routing to the source web-service, which is a service that implements the business logic. Use HttpClient to request web-service here

POST: this type of filters is executed after the ROUTING returns Response. It is used to modify Response results, collect statistics and transmit Response to the client.

ERROR: any error in any of the above three procedures is handled by a filters of type ERROR.

Zuul filters have the following key features:

Type (type): the type of Zuul filter, which determines the stage at which the filter is executed, for example, pre,post, etc.

Execution Order (order of execution): specifies the order in which the filter is executed. The smaller the value of Order, the more it is executed first.

Criteria (Standard): conditions required for Filters execution

Action (Action): execute Action (specific logic code) if the execution condition is met

Examples are as follows:

Public class MyFilter extends ZuulFilter {@ Override public Object run () {RequestContext ctx = RequestContext.getCurrentContext (); HttpServletRequest request = ctx.getRequest (); System.out.println (String.format ("% s AccessUserNameFilter request to% s", request.getMethod (), request.getRequestURL () .toString (); / / get the requested parameter String username = request.getParameter ("username") / / if the parameter of the request is not empty and the value is chhliu, the request is routed via if (null! = username & & username.equals ("chhliu")) {/ / a pair of ctx.setSendZuulResponse (true); ctx.setResponseStatusCode (200) / / set a value to let the next Filter see the status of the previous Filter ctx.set ("isSuccess", true); return null;} else {/ / filter the request without routing ctx.setSendZuulResponse (false); / / return error code ctx.setResponseStatusCode (401) / / return error content ctx.setResponseBody ("{\" result\ ":\" username is not correct!\ "}"); ctx.set ("isSuccess", false); return null;}} @ Override public boolean shouldFilter () {/ / whether the filter is executed. Here, true indicates that return true needs to be filtered. } @ Override public int filterOrder () {/ / priority is 0, the higher the number, the lower the priority return 0;} @ Override public String filterType () {/ / pre-filter return "pre";}}

The life cycle of the Zuul request is shown in the figure:

Fifth, set fuse breaker

Usually, a circuit breaker needs to be performed when the service cannot provide the service. The interface of FallbackProvider is needed to realize the circuit breaker on zuul. Implement two methods in the interface: getRoute () to specify which service to apply to; and fallbackResponse () to enter the execution logic of the circuit breaker function. Examples are as follows:

@ Componentpublic class CustomZuulFallbackHandler implements FallbackProvider {private final Logger logger = LoggerFactory.getLogger (FallbackProvider.class); / * specify the service * * @ return * / @ Override public String getRoute () {return "*";} public ClientHttpResponse fallbackResponse (String route) {return new ClientHttpResponse () {@ Override public HttpStatus getStatusCode () throws IOException {return HttpStatus.OK } @ Override public int getRawStatusCode () throws IOException {return 200;} @ Override public String getStatusText () throws IOException {return "OK";} @ Override public void close () {} @ Override public InputStream getBody () throws IOException {return new ByteArrayInputStream ((route+ "is unavailable.") .getBytes ()) } @ Override public HttpHeaders getHeaders () {HttpHeaders headers = new HttpHeaders (); headers.setContentType (MediaType.APPLICATION_JSON); return headers;}};} @ Override public ClientHttpResponse fallbackResponse (String route, Throwable cause) {if (cause! = null) {String reason = cause.getMessage (); logger.info ("Excption {}", reason);} return fallbackResponse (route) Sixth, Practice 6.1 pom file com.southgis.ibase.parent parentWebService 2.0.1-SNAPSHOT.. /.. / parent/parentWebService/pom.xml 4.0.0 api-gateway com.southgis.ibase.systemassistance 2.0.1-SNAPSHOT war Gateway Service org.springframework.cloud spring-cloud-starter-netflix -eureka-server org.springframework.cloud spring-cloud-config-client org.springframework.cloud spring-cloud-starter-netflix-zuul org.springframework.boot spring-boot-starter-web org.springframework .retry spring-retry org.jasig.cas.client cas-client-core org.springframework.boot spring-boot-starter-test test apiGateway org.springframework.boot Spring-boot-maven-plugin com.southgis.ibase.systemassistance.ApiGatewayCustomApplication repackage 6.2 Profil

Bootstrap.properties

# the {application} part of the spring.application.name=apiGateway# in the corresponding configuration file corresponds to the {profile} part of the spring.cloud.config.profile=dev2# configuration path in the previous configuration file. The server.servlet.context-path=/eureka-server# registry eureka.client.serviceUrl.defaultZone= http://localhost:8080/eureka-server/eureka# adds a similar prefix management.server.servlet.context-path=/apiGatewayeureka to the monitoring endpoint / info and / health endpoint. .instance.statusPageUrlPath = ${management.server.servlet.context-path} / actuator/infoeureka.instance.healthCheckUrlPath=$ {management.server.servlet.context-path} / actuator/health# through service connection configuration center # spring.cloud.config.discovery.enabled=true#spring.cloud.config.discovery.serviceId=config-serverspring.cloud.config.uri = http://localhost:8080/config-server# configuration file failed to quickly return spring.cloud.config.failFast=true# log configuration # logging.config=classpath:logback -spring.xml#logging.path=D:/ibase/logs/holiday#logging.pattern.console= [% d {yyyy-MM-dd HH:mm:ss}]-- [%-5p]: [% c]--% m% nroomlogging.progresn.file = [% d {yyyy-MM-dd HH:mm:ss}]-- [%-5p]: [% c] -% m% n

ApiGateway-dev2.properties

# access port server.port=8080# sets the session timeout to 540min. Server.servlet.session.timeout=PT540M# Zulu defaults to enabling default routing for all services for service security. Turn off the zuul.ignored-services=*# code dictionary service routing zuul.routes.codedict.path=/codedict/**zuul.routes.codedict.service-id=codedict# whether to forward the characters with forwarding characteristics zuul.routes.codedict.strip-prefix=false# administrative partition service routing zuul.routes.adminzone.path=/adminzone/**zuul.routes.adminzone.service-id=adminzonezuul.routes.adminzone.strip-prefix=false# whether to enable routing retry zuul.retryable=true# to the current service Number of retries of ribbon.MaxAutoRetries=2# switching instance timeout of ribbon.MaxAutoRetriesNextServer=0# request processing timeout of ribbon.ReadTimeout=6000# request connection ribbon.ConnectTimeout=6000# retries all operation requests ribbon.OkToRetryOnAllOperations=true# sets the timeout of hystrix to 5000 milliseconds (hystrix timeout is less than ribbon connection timeout Go first hystrix) hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds=50006.3 filter configuration @ Configurationpublic class ApiGatewayFilter extends ZuulFilter {@ Override public String filterType () {return "pre" } @ Override public int filterOrder () {return 0;} @ Override public boolean shouldFilter () {return true;} @ Override public Object run () throws ZuulException {RequestContext context = RequestContext.getCurrentContext (); HttpServletRequest request = context.getRequest (); Principal principal = request.getUserPrincipal (); / / get the user's login id String userId = principal.getName (); context.addZuulRequestHeader ("X-AUTH-ID", userId); return null;}}

Here, we set the acquired login user id to the request header and pass it to the internal service, which can be obtained through the following code:

String user = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes ()). GetRequest () .getHeader ("X-AUTH-ID"); 6.4 fuse configuration @ Componentpublic class CustomZuulFallbackHandler implements FallbackProvider {private final Logger logger = LoggerFactory.getLogger (FallbackProvider.class); / * * specify the service * * @ return * / @ Override public String getRoute () {return "*" } public ClientHttpResponse fallbackResponse (String route) {return new ClientHttpResponse () {@ Override public HttpStatus getStatusCode () throws IOException {return HttpStatus.OK;} @ Override public int getRawStatusCode () throws IOException {return 200;} @ Override public String getStatusText () throws IOException {return "OK" } @ Override public void close () {} @ Override public InputStream getBody () throws IOException {return new ByteArrayInputStream ((route+ "is unavailable.") .getBytes ());} @ Override public HttpHeaders getHeaders () {HttpHeaders headers = new HttpHeaders (); headers.setContentType (MediaType.APPLICATION_JSON); return headers;}} } @ Override public ClientHttpResponse fallbackResponse (String route, Throwable cause) {if (cause! = null) {String reason = cause.getMessage (); logger.info ("Excption {}", reason);} return fallbackResponse (route) * * @ author simon * * / @ SpringBootApplication (exclude = DataSourceAutoConfiguration.class) @ EnableZuulProxy@EnableEurekaClient@SpringCloudApplicationpublic class ApiGatewayMicroApplication {public static void main (String [] args) {SpringApplication.run (ApiGatewayMicroApplication.class, args);}} these are all the contents of the article "sample Analysis of Service Gateway SpringCloud Zuul". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

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

Development

Wechat

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

12
Report