Integrating Alibaba Sentinel with Spring Cloud Gateway for Rate Limiting and Circuit Breaking
This article demonstrates how to integrate Alibaba Sentinel into Spring Cloud Gateway for traffic rate limiting and circuit breaking, covering Maven dependencies, configuration of SentinelGatewayFilter and exception handler, rule definitions via YAML or Java code, and custom API grouping, providing a complete backend gateway protection guide.
1. Introduction
Alibaba Sentinel can be used to configure rate limiting and circuit breaking for mainstream API Gateways such as Spring Cloud Gateway , Netflix Zuul , etc. This guide shows how to replace Hystrix with Sentinel in a Spring Cloud Gateway project.
2. Integration Steps
2.1 Add Maven dependencies
Two options are provided. The simple way is to add only the sentinel-spring-cloud-gateway-adapter dependency; the full option also includes spring-cloud-starter-alibaba-sentinel (or its gateway variant).
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-spring-cloud-gateway-adapter</artifactId>
<version>x.y.z</version>
</dependency>For the full configuration replace the adapter with spring-cloud-alibaba-sentinel-gateway as shown:
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-sentinel-gateway</artifactId>
</dependency>2.2 Register Sentinel filter beans
@Configuration
public class GatewayConfiguration {
private final List
viewResolvers;
private final ServerCodecConfigurer serverCodecConfigurer;
public GatewayConfiguration(ObjectProvider
> viewResolversProvider,
ServerCodecConfigurer serverCodecConfigurer) {
this.viewResolvers = viewResolversProvider.getIfAvailable(Collections::emptyList);
this.serverCodecConfigurer = serverCodecConfigurer;
}
@Bean
@Order(Ordered.HIGHEST_PRECEDENCE)
public SentinelGatewayBlockExceptionHandler sentinelGatewayBlockExceptionHandler() {
// Register the block exception handler for Spring Cloud Gateway.
return new SentinelGatewayBlockExceptionHandler(viewResolvers, serverCodecConfigurer);
}
@Bean
@Order(Ordered.HIGHEST_PRECEDENCE)
public GlobalFilter sentinelGatewayFilter() {
return new SentinelGatewayFilter();
}
}2.3 Configure rate‑limiting rules
2.3.1 Using the Sentinel dashboard
spring:
cloud:
sentinel:
transport:
port: 8739
dashboard: 10.1.3.77:9090
eager: true
datasource:
ds:
nacos:
server-addr: 10.1.3.76:8848
dataId: ${spring.application.name}-sentinel
groupId: DEFAULT_GROUP
namespace: sms-dev
rule-type: flow
sentinel:
dashboard:
auth:
username: sentinel
password: sentinelExample JSON rule file (stored in Nacos):
[
{
"resource": "api-service",
"limitApp": "default",
"grade": 1,
"count": 2,
"strategy": 0,
"controlBehavior": 0,
"clusterMode": false
},
{
"resource": "url-proxy-1",
"limitApp": "default",
"grade": 1,
"count": 2,
"strategy": 0,
"controlBehavior": 0,
"clusterMode": false
}
]2.3.2 Defining rules in Java code
import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayFlowRule;
import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayRuleManager;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
@Configuration
public class GatewaySentinelConfiguration {
// ... constructor omitted for brevity ...
@PostConstruct
public void doInit() {
initGatewayRules();
initBlockHandler();
}
private void initGatewayRules() {
Set
rules = new HashSet<>();
rules.add(new GatewayFlowRule("url-proxy-1").setCount(1).setIntervalSec(60));
rules.add(new GatewayFlowRule("api-service").setCount(5).setIntervalSec(60));
GatewayRuleManager.loadRules(rules);
initCustomizedApis();
DegradeRule degradeRule = new DegradeRule("api-service")
.setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_RATIO)
.setCount(0.5)
.setTimeWindow(10);
DegradeRuleManager.loadRules(Collections.singletonList(degradeRule));
}
private void initBlockHandler() {
BlockRequestHandler blockRequestHandler = (exchange, throwable) -> {
Map
result = new HashMap<>(3);
result.put("code", String.valueOf(HttpStatus.TOO_MANY_REQUESTS.value()));
result.put("message", HttpStatus.TOO_MANY_REQUESTS.getReasonPhrase());
result.put("x", "xx");
return ServerResponse.status(HttpStatus.TOO_MANY_REQUESTS)
.contentType(MediaType.APPLICATION_JSON)
.body(BodyInserters.fromObject(result));
};
GatewayCallbackManager.setBlockHandler(blockRequestHandler);
}
private void initCustomizedApis() {
Set
definitions = new HashSet<>();
ApiDefinition api1 = new ApiDefinition("product-api")
.setPredicateItems(new HashSet
() {{
add(new ApiPathPredicateItem().setPattern("/product-service/product/**")
.setMatchStrategy(SentinelGatewayConstants.URL_MATCH_STRATEGY_PREFIX));
}});
ApiDefinition api2 = new ApiDefinition("order-api")
.setPredicateItems(new HashSet
() {{
add(new ApiPathPredicateItem().setPattern("/order-service/order/index"));
}});
definitions.add(api1);
definitions.add(api2);
GatewayApiDefinitionManager.loadApiDefinitions(definitions);
}
}3. Summary
If you use Sentinel, configure rate limiting and circuit‑breaking rules directly in the Sentinel dashboard.
Otherwise, Spring Cloud Gateway’s built‑in RequestRateLimiter and Hystrix can be used for similar protection.
Additional resources include the official Sentinel migration guide and the demo repository for Spring Cloud Gateway integration.
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.