Integrating Sentinel with Spring Cloud Gateway for Rate Limiting
This tutorial explains what gateway rate limiting is, shows how to integrate Alibaba Sentinel with Spring Cloud Gateway, details the configuration of Sentinel dashboard, gateway flow rules, API group management, implementation principles, and how to customize block responses for robust microservice protection.
1. What is Gateway Rate Limiting
In a micro‑service architecture the gateway isolates external calls from internal services; gateway rate limiting protects backend services by throttling traffic at the gateway layer.
Since Sentinel 1.6.0, Spring Cloud Gateway has built‑in support and offers two resource dimensions:
Route dimension: the resource name is the routeId defined in the routing configuration, suitable for coarse‑grained limiting of an entire micro‑service.
Custom API dimension: users can define API groups via Sentinel’s API, enabling fine‑grained limiting of specific URI patterns across multiple services.
2. Integrating Sentinel with Spring Cloud Gateway
Follow these steps to enable Sentinel in a gateway project:
1) Add Sentinel dependencies:
<!-- 引入sentinel进行服务降级熔断 -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
<!-- gateway网关整合sentinel进行限流降级 -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-sentinel-gateway</artifactId>
</dependency>2) Configure the Sentinel dashboard address in application.yml:
# sentinel看板相关配置
spring.cloud.sentinel.eager = true
spring.cloud.sentinel.transport.dashboard = 172.28.190.101:89993) Start the gateway with the additional JVM argument to mark the application as an API Gateway (not required when using the automatic integration):
# 注:通过 Spring Cloud Alibaba Sentinel 自动接入的 API Gateway 整合则无需此参数
-Dcsp.sentinel.app.type=1After these steps the gateway is monitored by the Sentinel console.
3. Sentinel Gateway Flow‑Control Rules
The core attributes of a GatewayFlowRule are:
resourceMode : RESOURCE_MODE_ROUTE_ID (route) or RESOURCE_MODE_CUSTOM_API_NAME (custom API).
resource : name of the route or custom API group.
grade : same dimension as the generic grade field in flow rules.
count : threshold value.
intervalSec : statistical time window (seconds, default 1).
controlBehavior : fast‑fail or warm‑up (queueing) mode, default fast‑fail.
burst : extra permits for traffic bursts.
maxQueueingTimeoutMs : maximum wait time in queueing mode.
paramItem : parameter‑based limiting configuration.
3.1 Parameter Item Details
parseStrategy defines how to extract a parameter (IP, Host, Header, URL param) using constants such as PARAM_PARSE_STRATEGY_CLIENT_IP, PARAM_PARSE_STRATEGY_HOST, PARAM_PARSE_STRATEGY_HEADER, PARAM_PARSE_STRATEGY_URL_PARAM.
fieldName specifies the header name or URL parameter name when the corresponding strategy is chosen.
pattern is a matching pattern; empty means all values are considered.
matchStrategy supports exact ( PARAM_MATCH_STRATEGY_EXACT), contains ( PARAM_MATCH_STRATEGY_CONTAINS) and regex ( PARAM_MATCH_STRATEGY_REGEX) matching.
3.2 API Group Management
API groups allow you to bind different rate‑limit policies to sets of interfaces. Three matching modes are available:
Exact mode: full path match, e.g., /order/1.
Prefix mode: path prefix match, e.g., /order/*.
Regex mode: regular‑expression match, e.g., \/order\/\d*.
4. Implementation Principle
When GatewayRuleManager loads GatewayFlowRule objects, Sentinel internally converts them into ParamFlowRule instances and stores them separately in GatewayRuleManager. During request processing, the Sentinel filter performs route/API‑group matching, extracts request attributes according to the rule, assembles a parameter array, and finally invokes SphU.entry(res, args). The GatewayFlowSlot added to the Slot Chain checks the generated hotspot‑parameter rules; if a rule does not target request attributes, a constant is appended to the parameter list to achieve ordinary flow control.
5. Is Gateway Limiting Enough?
Even with gateway‑level limiting, backend services can still be overwhelmed by internal calls (e.g., order service invoking product service during a flash‑sale). Therefore a combined strategy of gateway cluster limiting plus per‑service local limiting is recommended.
6. Customizing Block Responses
Sentinel allows custom block responses. Add the following configuration to return a JSON body when a request is throttled:
spring:
cloud:
sentinel:
scg:
fallback:
mode: response
response-status: 426
response-body: '{"code": 426,"message": "限流了,稍后重试!"}'Alternatively, configure a redirect mode:
spring:
cloud:
sentinel:
scg:
fallback:
mode: redirect
redirect: http://www.baidu.comWhen the limit is hit, the gateway will either return the JSON payload or redirect the client to the specified URL.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Selected Java Interview Questions
A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
