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 realize flow Control Breaking by integrating Spring Cloud Gateway with sentinel

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

Share

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

This article mainly introduces the relevant knowledge of "how Spring Cloud Gateway integrates sentinel to achieve flow control circuit breaker". The editor shows you the operation process through an actual case, and the operation method is simple, fast and practical. I hope this article "how to achieve flow control circuit breaker with Spring Cloud Gateway integration sentinel" can help you solve the problem.

1. What is gateway traffic restriction:

In the micro-service architecture, the gateway layer can shield the external services and directly invoke the internal services, and play the role of isolation and protection of the internal services. The gateway limit, as the name implies, is to limit the service flow through the gateway layer, so as to protect the back-end services.

Sentinel has provided Spring Cloud Gateway adaptation since version 1.6.0, which can limit the flow of two resource dimensions:

Route dimension: the routing entry configured in the configuration file, and the name of the resource is the corresponding routeId. This is a coarse-grained flow limit, which is usually used to limit the flow of a micro-service.

Custom API dimension: users can customize some API groups using the API provided by Sentinel. This is a fine-grained flow limit, which is matched for a certain type of uri and can span multiple micro services.

2. Gateway integrates sentinel to achieve gateway current limit:

So next we will introduce how spring cloud gateway integrates sentinel. As for how to build a gateway project and integrate a nacos registry, we have already introduced it in the last article. Interested readers please read this article: how to implement a micro-service gateway based on SpringCloudGateway.

1. Add sentinel related dependencies:

Com.alibaba.cloud spring-cloud-starter-alibaba-sentinel com.alibaba.cloud spring-cloud-alibaba-sentinel-gateway

2. Add the configuration of the sentinel console to the configuration file:

# sentinel Kanban related configuration spring.cloud.sentinel.eager = truespring.cloud.sentinel.transport.dashboard = 172.28.190.101VR 8999

3. Start the gateway project:

For the gateway project, we need to add the following launch parameters to the original launch parameters to mark the application as API Gateway:

# Note: API Gateway integration automatically accessed through Spring Cloud Alibaba Sentinel does not need this parameter-Dcsp.sentinel.app.type=1

4. Access the sentinel console:

At this point, we have integrated Spring Cloud Gateway and Sentinel, and when we enter the sentinel console, we can see that the gateway project is monitored.

Third, the introduction of sentinel gateway traffic control rules:

After integrating Spring Cloud Gateway and Sentinel, let's introduce how to control gateway traffic based on sentinel-dashboard console, as shown below:

3.1. Gateway traffic control rules:

The core attributes of gateway traffic control rule GatewayFlowRule are as follows:

① resourceMode: the rule is for the route of API Gateway (RESOURCE_MODE_ROUTE_ID) or the API packet defined by the user in Sentinel (RESOURCE_MODE_CUSTOM_API_NAME). The default is route.

② resource: resource name, which can be a route name in the gateway or a user-defined API packet name.

③ grade: current limit indicator dimension, grade field of the same current limit rule

④ count: current limiting threshold

⑤ intervalSec: statistical time window (in seconds). Default is 1 second.

⑥ controlBehavior: the control effect of traffic shaping. Currently, two modes, quick failure and uniform queuing, are supported. The default is fast failure.

⑦ burst: the number of additional requests allowed in response to sudden requests.

⑧ maxQueueingTimeoutMs: the maximum queue time (in milliseconds) in uniform queuing mode, which takes effect only in uniform queuing mode.

⑨ paramItem: parameter current limit configuration. If it is not provided, it means that the current is not limited for the parameters, and the gateway rule will be converted into a normal traffic control rule; otherwise, it will be converted into a hot spot rule. The fields are:

ParseStrategy: a policy for extracting parameters from a request. Four modes of extracting source IP (PARAM_PARSE_STRATEGY_CLIENT_IP), Host (PARAM_PARSE_STRATEGY_HOST), arbitrary Header (PARAM_PARSE_STRATEGY_HEADER) and arbitrary URL parameters (PARAM_PARSE_STRATEGY_URL_PARAM) are supported.

FieldName: if the extraction policy selects Header mode or URL parameter mode, you need to specify the corresponding header name or URL parameter name.

Pattern: the matching pattern of parameter values. Only the request attribute values that match this pattern will be included in statistics and flow control. If empty, all values of the request attribute will be counted.

MatchStrategy: the matching strategy for parameter values, which currently supports exact matching (PARAM_MATCH_STRATEGY_EXACT), substring matching (PARAM_MATCH_STRATEGY_CONTAINS) and regular matching (PARAM_MATCH_STRATEGY_REGEX).

3.2.Group management of API:

API grouping is to group interfaces, and then implement different current-limiting policies for different groups of interfaces.

(1) add API grouping:

As shown below, follow the specified steps to enter the custom API interface:

There are three configuration modes for API grouping: precise, prefix and regular.

Precise mode: when the path of the URL is exactly matched, the current is limited. For example, the matching string is configured as / order/1

Prefix mode: when the path prefix of URL is matched, the current is limited. For example, the matching string is configured as / order/*

Regular mode: when the path of the URL conforms to the regular expression rules, the current is limited. For example, the match string is configured as\ / order\ /\ d *

(2) configure current limit rules:

Next, you need to add a flow control rule to the API packet. The API name can be configured with a different API packet, as shown in the following figure:

After the addition, the current limit rule will take effect on the API that matches the matching pattern.

4. The principle of flow control implementation of sentinel gateway:

After knowing how to use sentinel-dashboard to control the flow of the gateway, we next introduce the implementation principle of the flow control of the sentinel gateway.

When loading gateway traffic control rules (GatewayFlowRule) through GatewayRuleManager, the underlying Sentinel will convert gateway traffic control rules into hotspot parameter rules (ParamFlowRule), regardless of whether the request attribute is restricted or not, which is stored in GatewayRuleManager and isolated from normal hotspot parameter rules. During the conversion, Sentinel will set the parameter index (idx) for the gateway traffic control rules according to the request attribute configuration, and synchronize them to the generated hotspot parameter rules.

When an external request enters the API Gateway, it goes through the filter implemented by Sentinel, in which the route / API packet matching-> request attribute parsing and parameter assembly are carried out in turn. Sentinel parses the request attributes according to the configured gateway traffic control rules, assembles the parameter array according to the parameter index order, and finally passes it into SphU.entry (res, args). The Sentinel API Gateway Adapter Common module adds a GatewayFlowSlot to the Slot Chain, which is specifically used to check gateway rules. GatewayFlowSlot extracts the generated hotspot parameter rules from GatewayRuleManager and checks the rules according to the passed parameters. If a rule is not specific to the request attribute, a preset constant will be placed at the last position of the parameter to achieve the effect of normal traffic control.

Will the service be secure if the gateway is restricted?

If current restrictions have been made at the gateway level, is the service hiding behind secure? The answer is no. In the micro-service architecture, an independent service is often called by multiple parties, as shown below:

Merchandise services are not only called by the gateway layer, but also by internal order services. At this time, if you only limit the flow at the gateway layer, once a large number of order services are requested, for example, the commodity services will be destroyed instantly if they do not do the current limit. Therefore, you need to limit the current for the services you are responsible for according to the company's business scenario. The most common solution: gateway layer cluster current limit + single machine current limit for internal services, so as to ensure that it will not be washed out by traffic.

6. Custom traffic control exception message:

The default exception return information of gateway traffic control is not humanized enough, and it is returned directly: "Block." this is definitely unacceptable, so how do we customize the configuration of traffic control exception information? In fact, sentinel has implemented the return content of custom flow control exceptions for us. Just add the configuration to the configuration file as follows:

Spring: cloud: sentinel: # response content after configuring current limit scg: fallback: # two modes: one is that response returns a text message, and the other is redirect, which redirects the jump. Need to configure redirect (uri of jump) mode: response # response status response-status: 426 # response body response-body:'{"code": 426, "message": "current limit, try again later!" }'

In the above configuration, mode is configured with response. Once the current is limited, the JSON string will be returned.

{"code": 426, "message": "current limit, try again later!" }

The configuration of redirection is as follows:

Spring: cloud: sentinel: # response content after configuring current limit scg: fallback: # # two modes: one is that response returns a text message, and the other is redirect, which redirects the jump. Need to configure redirect (jump uri) mode: redirect # # jump URL redirect: http://www.baidu.com on "Spring Cloud Gateway integration sentinel how to achieve flow control circuit breaker" content here, thank you for reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.

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