学习本篇文章之前如果你还没有了解过Sentinel
是什么的话,请先学习一下分布式系统的流量防卫兵Sentinel-入门指南。这样就这轻松学习Spring Cloud Alibaba Sentinel
的使用。
Sentinel 支持对 Spring Cloud Gateway
、Zuul
等主流的 API Gateway 进行限流。
Sentinel 1.6.0 引入了 Sentinel API Gateway Adapter Common
模块,此模块中包含网关限流的规则和自定义 API 的实体和管理逻辑:
其中网关限流规则 GatewayFlowRule 的字段解释如下:
route 名称
或者用户自定义的API 分组名称
。API Gateway
的route(RESOURCE_MODE_ROUTE_ID)
还是用户在 Sentinel 中定义的API 分组(RESOURCE_MODE_CUSTOM_API_NAME)
,默认是route
。grade
字段。1 秒
(目前仅对参数限流生效)。controlBehavior
字段,目前支持快速失败和匀速排队两种模式,默认是快速失败。(PARAM_PARSE_STRATEGY_CLIENT_IP)
、Host(PARAM_PARSE_STRATEGY_HOST)
、任意 Header(PARAM_PARSE_STRATEGY_HEADER)
和任意 URL 参数(PARAM_PARSE_STRATEGY_URL_PARAM)
四种模式。header 名称
或 URL 参数名称
。用户可以通过 GatewayRuleManager.loadRules(rules)
手动加载网关规则,或通过 GatewayRuleManager.register2Property(property)
注册动态规则源动态推送(推荐方式)。
当通过 GatewayRuleManager
加载网关流控规则(GatewayFlowRule)
时,无论是否针对请求属性进行限流,Sentinel 底层都会将网关流控规则转化为热点参数规则(ParamFlowRule)
,存储在GatewayRuleManager
中,与正常的热点参数规则相隔离。转换时 Sentinel 会根据请求属性配置,为网关流控规则设置参数索引(idx),并同步到生成的热点参数规则中。
外部请求进入 API Gateway 时会经过 Sentinel 实现的 filter
,其中会依次进行 路由/API 分组匹配
、请求属性解析
和参数组装
。Sentinel 会根据配置的网关流控规则来解析请求属性,并依照参数索引顺序组装参数数组,最终传入SphU.entry(res, args)
中。Sentinel API Gateway Adapter Common
模块向 Slot Chain
中添加了一个 GatewayFlowSlot
,专门用来做网关规则的检查。GatewayFlowSlot
会从GatewayRuleManager
中提取生成的热点参数规则,根据传入的参数依次进行规则检查。若某条规则不针对请求属性,则会在参数最后一个位置置入预设的常量,达到普通流控的效果。
从 1.6.0 版本开始,Sentinel 提供了 Spring Cloud Gateway
的适配模块,可以提供两种资源维度的限流:
routeId
API 分组
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-actuatorartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webfluxartifactId>
dependency>
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-starter-gatewayartifactId>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<optional>trueoptional>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
dependency>
<dependency>
<groupId>com.alibaba.cloudgroupId>
<artifactId>spring-cloud-alibaba-sentinel-gatewayartifactId>
<version>2.1.0.RELEASEversion>
dependency>
<dependency>
<groupId>com.alibaba.cloudgroupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discoveryartifactId>
<version>2.1.0.RELEASEversion>
dependency>
<dependency>
<groupId>com.alibaba.cspgroupId>
<artifactId>sentinel-transport-simple-httpartifactId>
<version>1.6.3version>
dependency>
<dependency>
<groupId>com.alibaba.cspgroupId>
<artifactId>sentinel-spring-cloud-gateway-adapterartifactId>
<version>1.6.3version>
dependency>
使用时只需注入对应的 SentinelGatewayFilter
实例以及 SentinelGatewayBlockExceptionHandler
实例即可。
@Configuration
public class GatewayConfiguration {
private final List<ViewResolver> viewResolvers;
private final ServerCodecConfigurer serverCodecConfigurer;
public GatewayConfiguration(ObjectProvider<List<ViewResolver>> 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(-1)
public GlobalFilter sentinelGatewayFilter() {
return new SentinelGatewayFilter();
}
}
server:
port: 9022 #提供者的端口
management:
endpoints:
web:
exposure:
include: '*'
logging:
level:
org.springframework.cloud.gateway: trace
org.springframework.http.server.reactive: debug
org.springframework.web.reactive: debug
reactor.ipc.netty: debug
spring:
application:
name: spring-cloud-gateway-service
main:
allow-bean-definition-overriding: true
spring:
cloud:
gateway:
enabled: true
discovery:
locator:
lower-case-service-id: true
routes:
# Add your routes here.
- id: aliyun_route
uri: https://www.aliyun.com/
predicates:
- Path=/product/**
- id: httpbin_route
uri: https://httpbin.org
predicates:
- Path=/httpbin/**
filters:
- RewritePath=/httpbin/(?>.*), /$\{segment}
#认证服务路由
- id: auth-service
predicates:
- Path=/auth-service/**
uri: lb://spring-cloud-nacos-auth-service
filters:
- StripPrefix=1
sentinel:
datasource.ds2.file:
file: "classpath: gateway.json"
ruleType: gw-flow
datasource.ds1.file:
file: "classpath: api.json"
ruleType: gw-api-group
nacos:
discovery:
server-addr: 192.168.10.200:8848
其中两个规则:api.json和gateway.json
[
{
"apiName": "some_customized_api",
"predicateItems": [
{
"pattern": "/product/baz"
},
{
"pattern": "/product/foo/**",
"matchStrategy": 1
},
{
"items": [
{
"pattern": "/spring-cloud/**"
},
{
"pattern": "/spring-cloud-alibaba/**"
}
]
}
]
},
{
"apiName": "another_customized_api",
"predicateItems": [
{
"pattern": "/ahas"
}
]
}
]
[
{
"resource": "some_customized_api",
"count": 1
},
{
"resource": "httpbin_route",
"count": 0,
"paramItem": {
"parseStrategy": 2,
"fieldName": "Spring-Cloud-Alibaba"
}
},
{
"resource": "httpbin_route",
"count": 0,
"paramItem": {
"parseStrategy": 3,
"fieldName": "name"
}
}
]
同时自定义了一些 API 分组:
private void initCustomizedApis() {
Set<ApiDefinition> definitions = new HashSet<>();
ApiDefinition api1 = new ApiDefinition("some_customized_api")
.setPredicateItems(new HashSet<ApiPredicateItem>() {{
add(new ApiPathPredicateItem().setPattern("/ahas"));
add(new ApiPathPredicateItem().setPattern("/product/**")
.setMatchStrategy(SentinelGatewayConstants.URL_MATCH_STRATEGY_PREFIX));
}});
ApiDefinition api2 = new ApiDefinition("another_customized_api")
.setPredicateItems(new HashSet<ApiPredicateItem>() {{
add(new ApiPathPredicateItem().setPattern("/**")
.setMatchStrategy(SentinelGatewayConstants.URL_MATCH_STRATEGY_PREFIX));
}});
definitions.add(api1);
definitions.add(api2);
GatewayApiDefinitionManager.loadApiDefinitions(definitions);
}
同时也定义一些route纬度:
private void initGatewayRules() {
Set<GatewayFlowRule> rules = new HashSet<>();
rules.add(new GatewayFlowRule("aliyun_route")
.setCount(10)
.setIntervalSec(1)
);
rules.add(new GatewayFlowRule("aliyun_route")
.setCount(2)
.setIntervalSec(2)
.setBurst(2)
.setParamItem(new GatewayParamFlowItem()
.setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_CLIENT_IP)
)
);
rules.add(new GatewayFlowRule("httpbin_route")
.setCount(10)
.setIntervalSec(1)
.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_RATE_LIMITER)
.setMaxQueueingTimeoutMs(600)
.setParamItem(new GatewayParamFlowItem()
.setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_HEADER)
.setFieldName("X-Sentinel-Flag")
)
);
rules.add(new GatewayFlowRule("httpbin_route")
.setCount(1)
.setIntervalSec(1)
.setParamItem(new GatewayParamFlowItem()
.setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_URL_PARAM)
.setFieldName("pa")
)
);
rules.add(new GatewayFlowRule("httpbin_route")
.setCount(2)
.setIntervalSec(30)
.setParamItem(new GatewayParamFlowItem()
.setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_URL_PARAM)
.setFieldName("type")
.setPattern("warn")
.setMatchStrategy(SentinelGatewayConstants.PARAM_MATCH_STRATEGY_CONTAINS)
)
);
rules.add(new GatewayFlowRule("some_customized_api")
.setResourceMode(SentinelGatewayConstants.RESOURCE_MODE_CUSTOM_API_NAME)
.setCount(5)
.setIntervalSec(1)
.setParamItem(new GatewayParamFlowItem()
.setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_URL_PARAM)
.setFieldName("pn")
)
);
/**
* 手动加载网关规则
*/
GatewayRuleManager.loadRules(rules);
}
那么这里面的 route ID(如 product_route)和 API name(如 some_customized_api)都会被标识为 Sentinel 的资源。比如访问网关的 URL 为 http://localhost:9022/product/ahas
的时候,对应的统计会加到 product_route
和 some_customized_api
这两个资源上面,而 http://localhost:8090/httpbin/json
只会对应到 httpbin_route
资源上面。
您可以在 GatewayCallbackManager
注册回调进行定制:
setBlockHandler
:注册函数用于实现自定义的逻辑处理被限流的请求,对应接口为 BlockRequestHandler
。默认实现为 DefaultBlockRequestHandler
,当被限流时会返回类似于下面的错误信息:Blocked by Sentinel: FlowException
。package com.lidong.gateway;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* 开启服务发现
*/
@SpringBootApplication
public class SentinelGatewayApplication {
public static void main(String[] args) {
SpringApplication.run(SentinelGatewayApplication.class, args);
}
}
<dependency>
<groupId>com.alibaba.cspgroupId>
<artifactId>sentinel-transport-simple-httpartifactId>
<version>1.6.3version>
dependency>
添加启动参数
-Dcsp.sentinel.app.type=1 -Dcsp.sentinel.dashboard.server=localhost:8080 -Dproject.name=gateway-sentinel
csp.sentinel.app.type=1 代表网关类型
java -jar gateway-sentinel.jar -Dcsp.sentinel.app.type=1 -Dcsp.sentinel.dashboard.server=localhost:8080 -Dproject.name=gateway-sentinel
然后通过网关访问
http://localhost:9022/product/ahas
Sentinel 1.6.3 引入了网关流控控制台的支持,用户可以直接在 Sentinel 控制台上查看 API Gateway 实时的 route
和自定义 API
分组监控,管理网关规则和 API 分组配置。
我们可以在控制台配置自定义的 API 分组,将一些 URL 匹配模式归为一个 API 分组:
然后我们可以在控制台针对预设的 route ID 或自定义的 API 分组配置网关流控规则
到这里一个简单spring-cloud-alibaba-sentinel-gateway网关的案例基本上就完成了。
本案例的源代码已经上传github :https://github.com/lidong1665/spring-cloud-learning-example/tree/master/spring-cloud-gateway-service-sentinel