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

What are the knowledge points of SpringCloud?

2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article introduces the relevant knowledge of "what are the knowledge points of SpringCloud". In the operation of actual 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!

Get to know Spring Cloud Gateway

Spring Cloud Gateway is an API gateway based on Spring 5 Magi Project Reactor and Spring Boot 2, and is one of the main components of Spring Cloud microservice ecology. Spring Cloud Gateway is mainly responsible for routing and distributing interface requests, and supports extended operations such as security verification, traffic monitoring and flow control of requests. It is also worth mentioning that Spring Cloud Gateway defaults to the non-blocking Icano model to realize the distribution of request routes. Compared with others, the gateway performance of synchronous blocking Icano model written in Java is higher and the number of concurrency is higher than others, which avoids the thread idle caused by Imayo blocking (network calls, database operations, etc.) and can continue to respond to other requests.

Spring Cloud Gateway applicable scenario

As an API gateway, Spring Cloud Gateway also provides powerful functions, such as load balancing, dynamic routing, access control, current-limiting circuit breaker, burial point monitoring and other functions. If the existing micro-service system is based on Java ecology or even Spring ecology, then it is very suitable to use Spring Cloud Gateway as the API application gateway, allowing aggregation to manage multiple micro-service API for unified output.

At the same time, adhering to the tradition of the Spring family, Spring Cloud Gateway also aims to provide a simple and efficient way to expand API routing and request concerns. For developers who are already familiar with Spring or Spring Boot, the cost of learning Spring Cloud Gateway is not high. Using the annotation-driven and automated configuration features brought by the underlying framework, it is not difficult to use and expand.

Get started with Spring Cloud Gateway quickly

Using Spring Cloud Gateway can quickly build an API gateway, but before that, introduce some special concepts involved in using the Spring Cloud Gateway framework to deepen the understanding of Spring Cloud Gateway and facilitate later use.

Routing: is the basic component of Spring Cloud Gateway and usually consists of an id identity, a target URI, and a series of Predicate and filters.

Predicate: the Predicate object of the Java 8 function library. The specific type is Predicate. It is used to match the data information on the HTTP request, such as request header information and request body information. If the assertion for a request is true, the route associated with it is considered a match, and the request is then sent to that route for processing.

Filter: components used to modify the request or response of a route need to implement the GatewayFilter interface in Spring Cloud Gateway and need to be constructed by concrete implementation classes based on GatewayFilterFactory.

After understanding the above three concepts, and looking at the figure above, we can clearly see how Spring Cloud Gateway handles client requests, which helps us to make good use of Spring Cloud Gateway.

The client request is first obtained by GatewayHandlerMapping, and then the corresponding route is found according to the assertion match.

After finding the route, go through the processing method of the associated set of request filters, request to the service program corresponding to the target URI, and get the service response.

After the gateway receives the response, after passing the processing method of the associated response filter, the GatewayHandlerMapping also returns the response to the client.

In addition, it should be noted that the filter of Spring Cloud Gateway is executed sequentially, and the execution order is determined by the size of the order value. The smaller the value, the higher the priority, the earlier the execution.

How to achieve API aggregation

After understanding the overall request processing process of Spring Cloud Gateway, let's quickly build a Spring Cloud Gateway-based API gateway to see what else we need to pay attention to in practical application. It is important to note that the Spring Cloud Gateway used in this article is the latest milestone version 2.2.3, the corresponding Spring Boot version is 2.3.1, and the Spring Cloud version is Hoxton.SR6. Using Spring Initializr, select the corresponding version and quickly create a new project spring-cloud-gateway-quick-start after dependency, and in order to achieve the routing of the request and show the effect of the gateway, create a user service application demo-userservice and an order service application demo-orderservice respectively, each providing a callable API interface.

User service exposes port 8071 and provides / user/get interface:

/ / demo-userservice Project @ RestController @ RequestMapping ("/ user") public class UserServiceController {@ RequestMapping ("/ get") public User get () {return User.mock ();}}

Similarly, the order service exposes port 8061 and provides / order/get interface:

/ / demo-orderservice Project @ RestController @ RequestMapping ("/ order") public class OrderServiceController {@ RequestMapping ("/ get") public Order get () {return Order.mock ();}}

Next, to aggregate the two service interfaces into the spring-cloud-gateway-quick-start project through Spring Cloud Gateway, first take a look at the implementation using Spring Cloud Gateway API:

@ SpringBootApplication public class DemogatewayApplication {public static void main (String [] args) {SpringApplication.run (DemogatewayApplication.class, args) } @ Bean public RouteLocator customRouteLocator (RouteLocatorBuilder builder) {return builder.routes () .route ("user-service", r-> r.path ("/ user/*") .uri ("http://localhost:8071")) .route (" order-service ", r-> r.path (" / order/* ") .uri (" http://localhost:8061")) .build ()) " }}

Next, to aggregate the two service interfaces into the spring-cloud-gateway-quick-start project through Spring Cloud Gateway, first take a look at the implementation using Spring Cloud Gateway API:

The above code has already implemented the function of API routing. Is it very fast to start spring-cloud-gateway-quick-start and other service applications at the same time, and you can access user services and order services through gateway applications:

One@192 ~% curl http://localhost:8080/user/get {"id": 4720186416534735290, "token": "86b6118d-7dc6-4d30-a5f3-3d5fc6348f9a"} one@192 ~% curl http://localhost:8080/order/get {"id": 5832646761962425508, "title": "My Order"}

Going back to the code of the API implementation, the DemogatewayApplication#customRouteLocator method defines two routes with id of user-service and order-service, and sets the assertion that matches the request, as well as the real target request address. Here, the route assertion adopts the rule of path matching, and the route can be matched as long as the original request address conforms to the corresponding rules. However, Spring Cloud Gate also supports rich assertion rules, such as host matching, request body field matching, request data matching, and so on, which are sufficient to meet the rules of custom route assertions.

Because using API is a hard-coded way to define routing rules in the program, this is not scalable and difficult to maintain. Therefore, another implementation method is recommended: configuration. Let's take a look at how to configure the same function in application.properties:

Spring.cloud.gateway.routes [0] .id=order-service spring.cloud.gateway.routes [0] .uri = http://localhost:8061 spring.cloud.gateway.routes [0] .dispensates [0] .name = Path spring.cloud.gateway.routes [0] .formulates [0] .args [pattern] = / order/* spring.cloud.gateway.routes [1] .id=user-service spring.cloud.gateway.routes [1] .uri = http://localhost:8071 spring.cloud.gateway.routes [1] .principates [0] ] .name=Path spring.cloud.gateway.routes [1] .principates [0] .args [pattern] = / user/*

Using the above configuration, restarting the gateway application can also achieve the effect of the previous API mode. Because the routing rules are transferred to the configuration file, it greatly facilitates the management of API and provides the possibility for the realization of dynamic routing. Of course, we need to implement dynamic routing, in addition to routing configuration, we also need to expand to achieve dynamic refresh of routing rules, which involves the more advanced usage of Spring Cloud Gateway. This article will not elaborate on it in detail. We can wait for subsequent articles on advanced use and analysis or refer to other implementation materials on the Internet.

How to customize a filter

In order to handle the request or response of API, Spring Cloud Gateway provides filter components to implement this function, and has many powerful built-in functions. In addition, there are two types of filters, the global filter and the gateway filter. For the global filter, all requests matching to the route will be processed by the global filter, while the gateway filter will play a role only when it is displayed on the specified route.

There are 8 default global filters for Spring Cloud Gateway:

ForwardRoutingFilter

LoadBalancerClientFilter (deprecated)

ReactiveLoadBalancerClientFilter

WebClientHttpRoutingFilter

NettyWriteResponseFilter

RouteToRequestUrlFilter

WebsocketRoutingFilter

GatewayMetricsFilter

There are more gateway filters, and they are constructed by corresponding factory classes, such as HystrixGatewayFilterFactory for circuit breakers, RequestRateLimiterGatewayFilterFactory for current limit, ModifyRequestBodyGatewayFilterFactory for modifying request data, and so on. Developers are also allowed to define their own filters.

First, let's take a look at how to customize a global filter. The code implementation is relatively simple:

@ Component public class CustomGlobalFilter implements GlobalFilter, Ordered {private Logger log = LoggerFactory.getLogger (MyAuthFilterFactory.class); @ Override public Mono filter (ServerWebExchange exchange, GatewayFilterChain chain) {log.info ("execute Custom filter"); return chain.filter (exchange);} @ Override public int getOrder () {return-1;}}

This allows you to add a global filter for all routes. Different from the definition of the global filter, the gateway filter must be declared on the specified route before it can take effect. Refer to the official built-in gateway blocker, you can customize a simple gateway blocker factory for authorization as follows:

@ Component public class MyAuthGatewayFilterFactory extends AbstractGatewayFilterFactory {private Logger logger = LoggerFactory.getLogger (MyAuthGatewayFilterFactory.class); public MyAuthGatewayFilterFactory () {super (Config.class);} @ Override public GatewayFilter apply (Config config) {return new GatewayFilter () {@ Override public Mono filter (ServerWebExchange exchange, GatewayFilterChain chain) {ServerHttpRequest request = exchange.getRequest () MultiValueMap queryParams = request.getQueryParams (); String from = queryParams.getFirst (config.getAuthKey ()); ServerHttpResponse response = exchange.getResponse (); logger.warn ("Verification Authorization starts"); if (config.getAuthValue (). Equals (from)) {logger.warn ("Verification Authorization successful") Return chain.filter (exchange);} else {logger.warn ("verify authorization failed"); response.setStatusCode (HttpStatus.OK); response.getHeaders () .setContentType (MediaType.valueOf ("text/html;charset=utf-8")) DataBuffer wrap = response.bufferFactory () .wrap (config.getAuthFailMsg () .getBytes (Charset.forName ("UTF-8")); return response.writeWith (Flux.just (wrap));};} public static class Config {private String authKey = "from"; private String authValue = "system" Private String authFailMsg = "authorization failed"; public String getAuthKey () {return authKey;} public void setAuthKey (String authKey) {this.authKey = authKey;} public String getAuthValue () {return authValue;} public void setAuthValue (String authValue) {this.authValue = authValue } public String getAuthFailMsg () {return authFailMsg;} public void setAuthFailMsg (String authFailMsg) {this.authFailMsg = authFailMsg;}

If you want to use under user-service routing, you need to add the following configuration to the application.properties configuration file:

Spring.cloud.gateway.routes [1] .name [0] .name = MyAuth

The name here needs to be consistent with the MyAuth of the MyAuthGatewayFilterFactory class. Spring Cloud Gateway will automatically concatenate the AuthGatewayFilterFactory to find the corresponding gateway filter. Failure to find it will cause startup failure and throw an exception:

Java.lang.IllegalArgumentException: Unable to find GatewayFilterFactory with name MyAuth3

When the gateway application is configured to restart, the original method is used to request the user service. It can no longer be accessed normally. Only the information of verification authorization failure is returned. The data can only be obtained successfully by accessing it in http://localhost:8080/user/get?from=system mode, indicating that the defined authorization interceptor has worked.

Here we customize both the global interceptor and the gateway interceptor, which is usually extended on the gateway interceptor and used in conjunction with the built-in filter.

This is the end of the content of "what are the knowledge points of SpringCloud". Thank you for your 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

Development

Wechat

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

12
Report