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 analyze and construct the actual Operation and principle of Spring Cloud Gateway Gateway

2025-03-04 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

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

Today, I will talk to you about how to analyze the actual combat and principle of building a Spring Cloud Gateway gateway. Many people may not know much about it. In order to make you understand better, the editor has summarized the following contents for you. I hope you can gain something according to this article.

API Gateway

The reason for the emergence of the API gateway is the emergence of the micro-service architecture. Different micro-services generally have different network addresses, and external clients may need to call the interfaces of multiple services to complete a business requirement. If the client is allowed to communicate with each micro-service directly, there will be the following problems:

The client will request different micro-services many times, which increases the complexity of the client.

There are cross-domain requests, which are relatively complex to deal with in certain scenarios.

Authentication is complex, and each service needs independent authentication.

It is difficult to ReFactor, and as the project iterates, micro-services may need to be redivided. For example, you might merge multiple services into one or split a service into multiple services. If the client communicates directly with the microservice, refactoring will be difficult to implement.

Some micro-services may use firewall / browser-unfriendly protocols, which can be difficult to access directly.

The above problems can be solved with the help of API gateway. The API gateway is the middle layer between the client and the server, and all external requests will pass through the API gateway first. In other words, the implementation of API pays more attention to business logic, while security, performance and monitoring can be left to the API gateway to improve business flexibility without lack of security. A typical architecture diagram is shown in the figure:

The advantages of using the API gateway are as follows:

Easy to monitor. Monitoring data can be collected at the gateway and pushed to an external system for analysis.

Easy to authenticate. Authentication can be performed on the gateway and then the request can be forwarded to the back-end micro-service without having to authenticate in each micro-service.

The number of interactions between the client and various micro-services is reduced.

API gateway selection

The situation of the industry:

An empty project package for spring-cloud-gateway-example is produced at this time, and the pom.xml file is as follows

4.0.0 org.springframework.boot spring-boot-starter-parent 2.1.3.RELEASE com.example spring-cloud-gateway-example 0.0.1-SNAPSHOT spring-cloud-gateway-example Demo project for Spring Boot 1.8 Greenwich.RELEASE org.springframework.cloud spring-cloud-starter-gateway Org.springframework.boot spring-boot-starter-test test org.springframework.cloud spring-cloud-dependencies ${spring-cloud.version} pom import Org.springframework.boot spring-boot-maven-plugin spring-milestones Spring Milestones https://repo.spring.io/milestone

two。 Create a configuration class GatewayRoutes for a Route instance

Package com.example.springcloudgatewayexample;import org.springframework.cloud.gateway.route.RouteLocator;import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration @ Configurationpublic class GatewayRoutes {@ Bean public RouteLocator routeLocator (RouteLocatorBuilder builder) {return builder.routes () .route (r-> r.path ("/ java/**") .route (f-> f.stripPrefix (1) ) .uri ("http://localhost:8090/helloWorld")) .build () }}

Of course, you can not apply the configuration class and use the configuration file, as shown in the following figure

Spring: cloud: gateway: routes:-predicates:-Path=/java/** filters:-StripPrefix=1 uri: "http://localhost:8090/helloWorld"

However, for debugging convenience, we use the configuration class approach.

At this point, the project has been completed, which is simple enough.

3. Start this project

> > because the api gateway needs to be forwarded to a service, this article is http://localhost:8090/helloWorld, so you need to start me above. You can also create a normal web project, set the startup port to 8090, and then start it.

. _ _ _ (() _ _ _ (() _ _ _ |'_ _ _ | |'_ _ / _ _ _ | | | (_ |)'| _ _ _ | . _ | _ | | _ | _ | | _ | | / = | _ | = | _ _ / = / _ /:: Spring Boot:: (v2.1.3.RELEASE) 2019-02-21 0929 INFO 07.450 INFO 11704-[main] c.e.demo.Spring5WebfluxApplication: Starting Spring5WebfluxApplication on DESKTOP-405G2C8 with PID 11704 (E:\ workspaceForCloud\ spring5-webflux\ target\ classes started by dell in E:\ workspaceForCloud\ spring5-webflux) 2019-02-21 0929 INFO 11704 [main] c.e.demo.Spring5WebfluxApplication: No active profile set Falling back to default profiles: default2019-02-21 009 INFO 29 INFO 11704-[main] o.s.b.web.embedded.netty.NettyWebServer: Netty started on port (s): 80902019-02-21 09 9 main 29 Swiss 09.413 INFO 11704-[main] c.e.demo.Spring5WebfluxApplication: Started Spring5WebfluxApplication in 2.304 seconds (JVM running for 7.311)

> > start the spring-cloud-gateway-example project in spring boot mode, with the following log

2019-02-21 10 INFO 34Bean 33.435 INFO 8580-[main] trationDelegate$BeanPostProcessorChecker: Bean 'org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration' of type [org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration$$EnhancerBySpringCGLIB$$1e059320] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying). _ _ / / _ _ _ (() _ _ _ |'_ _ _ | |\ / _ _ _ | | | (_ _ | |) )'| _ |. _ _ | _ | | _ | _ | | _\ _ _ | | / = | _ | = | _ _ / = / _ /:: Spring Boot:: (v2.1.3.RELEASE) 2019-02-21 10 INFO 33.767 INFO 8580-[main] e.s.SpringCloudGatewayExampleApplication: No active profile set | Falling back to default profiles: default2019-02-21 10 INFO 34.219 INFO 8580-[main] o.s.cloud.context.scope.GenericScope: BeanFactory id=d98183ec-3e46-38ba-ba4c-e976a1017dce2019-02-21 10 INFO 34.243 INFO 8580-[main] trationDelegate$BeanPostProcessorChecker: Bean 'org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration' of type [org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration$$EnhancerBySpringCGLIB$$1e059320] is not eligible for getting processed by all BeanPostProcessors (for example) : not eligible for auto-proxying) 2019-02-21 10 o.s.c.g.r.RouteDefinitionRouteLocator INFO 8580-[main] o.s.c.g.r.RouteDefinitionRouteLocator: Loaded RoutePredicateFactory [After] 2019-02-21 10 o.s.c.g.r.RouteDefinitionRouteLocator 34 o.s.c.g.r.RouteDefinitionRouteLocator 44.367 INFO 8580-[main] o.s.c.g.r.RouteDefinitionRouteLocator: Loaded RoutePredicateFactory [Before] 2019-02-21 10 Switzerland 3444.367 INFO 8580-[ Main] o.s.c.g.r.RouteDefinitionRouteLocator: Loaded RoutePredicateFactory [Between] 2019-02-21 10 o.s.c.g.r.RouteDefinitionRouteLocator: Loaded RoutePredicateFactory [Header] 2019-02-21 10: [main] o.s.c.g.r.RouteDefinitionRouteLocator: Loaded RoutePredicateFactory [Cookie] 2019-02-21 10 o.s.c.g.r.RouteDefinitionRouteLocator: Loaded RoutePredicateFactory [Header] 2019-02-21 10: 34Loaded RoutePredicateFactory 44.368 INFO 8580-[main] o.s.c.g.r.RouteDefinitionRouteLocator: Loaded RoutePredicateFactory [Host] 2019-02-21 10 o.s.c.g.r.RouteDefinitionRouteLocator 3444.368 INFO 8580-[main] o.s.c.g.r.RouteDefinitionRouteLocator: Loaded RoutePredicateFactory [Method] 2019-02-21 10 o.s.c.g.r.RouteDefinitionRouteLocator 44.368 INFO 8580-- [main] o.s.c.g.r.RouteDefinitionRouteLocator : Loaded RoutePredicateFactory [Path] 2019-02-21 10 INFO 44.368 INFO 8580-[main] o.s.c.g.r.RouteDefinitionRouteLocator: Loaded RoutePredicateFactory [Query] 2019-02-21 10 INFO 3415 44.368 INFO 8580-[main] o.s.c.g.r.RouteDefinitionRouteLocator: Loaded RoutePredicateFactory [ReadBodyPredicateFactory] 2019-02-21 10 color 34Switzerland 44.368 INFO 8580-[ Main] o.s.c.g.r.RouteDefinitionRouteLocator: Loaded RoutePredicateFactory [RemoteAddr] 2019-02-21 10 INFO 44.368 INFO 8580-[main] o.s.c.g.r.RouteDefinitionRouteLocator: Loaded RoutePredicateFactory [Weight] 2019-02-21 10 10 o.s.c.g.r.RouteDefinitionRouteLocator: Loaded RoutePredicateFactory [CloudFoundryRouteService] 2019-02-21 10: 34Netty started on port 44.920 INFO 8580-[main] o.s.b.web.embedded.netty.NettyWebServer: Netty started on port (s): 80802019-02-21 10 Netty started on port: 44.923 INFO 8580-[main] e.s.SpringCloudGatewayExampleApplication: Started SpringCloudGatewayExampleApplication in 12.329 seconds (JVM running for 13.126)

4. Testing, browsers access http://localhost:8080/java/helloWorld

Return to hello world!

5. From the above code and configuration and example, we can see that the flow of spring cloud gateway processing request requests is as follows:

That is, at the front end, a netty server (default port is 8080) is launched to accept requests, and then through Routes (each Route is processed by Predicate (equivalent to HandlerMapping) and Filter (equivalent to HandlerAdapter), and then sent to the response via Netty Client.

So the most important thing in gateway itself should be Route (Netty Server and Client have been packaged), which is built by RouteLocatorBuilder and contains Predicate and Filter internally.

Private Route (String id, URI uri, int order, AsyncPredicate predicate, List gatewayFilters) {this.id = id; this.uri = uri; this.order = order; this.predicate = predicate; this.gatewayFilters = gatewayFilters;}

So let's talk about these two components.

5.1.Predicate

Predicte is built by PredicateSpec, and the main implementations are:

Take path as an example

/ * * A predicate that checks if the path of the request matches the given pattern * @ param patterns the pattern to check the path against. * The pattern is a {@ link org.springframework.util.PathMatcher} pattern * @ return a {@ link BooleanSpec} to be used to add logical operators * / public BooleanSpec path (String... Patterns) {return asyncPredicate (getBean (PathRoutePredicateFactory.class) .applyAsync (c-> c.setPatterns (Arrays.asList (patterns);}

Execute in PathRoutePredicateFactory

@ Override public Predicate apply (Config config) {final ArrayList pathPatterns = new ArrayList (); synchronized (this.pathPatternParser) {pathPatternParser.setMatchOptionalTrailingSeparator (config.isMatchOptionalTrailingSeparator ()); config.getPatterns () .forEach (pattern-> {PathPattern pathPattern = this.pathPatternParser.parse (pattern); pathPatterns.add (pathPattern);}) } return exchange-> {PathContainer path = parsePath (exchange.getRequest (). GetURI (). GetPath ()); Optional optionalPathPattern = pathPatterns.stream () .filter (pattern-> pattern.matches (path)) .findFirst (); if (optionalPathPattern.isPresent ()) {PathPattern pathPattern = optionalPathPattern.get () TraceMatch ("Pattern", pathPattern.getPatternString (), path, true); PathMatchInfo pathMatchInfo = pathPattern.matchAndExtract (path); putUriTemplateVariables (exchange, pathMatchInfo.getUriVariables ()); return true;} else {traceMatch ("Pattern", config.getPatterns (), path, false); return false }};}

5.2.Filter

There are two kinds of Filter, one is GatewayFilter, the other is GlobalFilter

5.2.1 GatewayFilter

GatewayFilter is built by GatewayFilterSpec, the builder of GatewayFilter

5.3 connection between GlobalFilter and GatewayFilter

FilteringWebHandler.GatewayFilterAdapter represented GlobalFilter.

6. Summary

This paper starts with an example of spring-cloud-gateway, briefly introduces the components of spring-cloud-gateway, and gives the principle of implementation from the point of view of source code.

Spring-cloud-gateway is at the front end, initiating a netty server (default port is 8080) to accept requests, and then sending responses via Netty Client through Routes (each Route is processed by Predicate (equivalent to HandlerMapping) and Filter (equivalent to HandlerAdapter) and sent to the response via Netty Client.

The various implementations of Predicate and Filter define the functionality that spring-cloud-gateway has.

After reading the above, do you have any further understanding of how to analyze the actual combat and principle of building a Spring Cloud Gateway gateway? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.

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