《SpringCloudAlibaba+Nacos整合Gateway网关》
《Spring Cloud Gateway过滤器(GatewayFilter)工厂》
《Spring Cloud Gateway内置各类型Predicate(断言)使用说明》
1、简介
网关是所有请求的公共入口,所以可以在网关进行限流,而且限流的方式也很多,通过Sentinel组件来实现网关的限流。Sentinel支持对SpringCloud Gateway、Zuul等主流网关进行限流。
实现限流机制主要由GatewayFlowRule
与ApiDefinition
两个核心类实现配置:
- GatewayFlowRule: 网关限流规则,针对 API Gateway 的场景定制的限流规则,可以针对不同 route 或自定义的 API 分组进行限流,支持针对请求中的参数、Header、来源 IP 等进行定制化的限流。
- ApiDefinition: 用户自定义的 API 定义分组,可以看做是一些 URL 匹配的组合。比如我们可以定义一个 API 叫 my_api,请求 path 模式为 /foo/** 和 /baz/** 的都归到 my_api 这个 API 分组下面。限流的时候可以针对这个自定义的 API 分组维度进行限流。
其中网关限流规则 GatewayFlowRule
的字段解释如下:
- resource:资源名称,可以是网关中的 route 名称或者用户自定义的 API 分组名称。
- resourceMode:规则是针对 API Gateway 的 route(RESOURCE_MODE_ROUTE_ID)还是用户在 Sentinel 中定义的 API 分组(RESOURCE_MODE_CUSTOM_API_NAME),默认是 route。
- grade:限流指标维度,同限流规则的 grade 字段。
- count:限流阈值
- intervalSec:统计时间窗口,单位是秒,默认是 1 秒。
- controlBehavior:流量整形的控制效果,同限流规则的 controlBehavior 字段,目前支持快速失败和匀速排队两种模式,默认是快速失败。
- burst:应对突发请求时额外允许的请求数目。
- maxQueueingTimeoutMs:匀速排队模式下的最长排队时间,单位是毫秒,仅在匀速排队模式下生效。
- paramItem:参数限流配置。若不提供,则代表不针对参数进行限流,该网关规则将会被转换成普通流控规则;否则会转换成热点规则。其中的字段:
- parseStrategy:从请求中提取参数的策略,目前支持提取来源 IP(PARAM_PARSE_STRATEGY_CLIENT_IP)、Host(PARAM_PARSE_STRATEGY_HOST)、任意 Header(PARAM_PARSE_STRATEGY_HEADER)和任意 URL 参数(PARAM_PARSE_STRATEGY_URL_PARAM)四种模式。
- fieldName:若提取策略选择 Header 模式或 URL 参数模式,则需要指定对应的 header 名称或 URL 参数名称。
- pattern:参数值的匹配模式,只有匹配该模式的请求属性值会纳入统计和流控;若为空则统计该请求属性的所有值。(1.6.2 版本开始支持)
- matchStrategy:参数值的匹配策略,目前支持精确匹配(PARAM_MATCH_STRATEGY_EXACT)、子串匹配(PARAM_MATCH_STRATEGY_CONTAINS)和正则匹配(PARAM_MATCH_STRATEGY_REGEX)。(1.6.2 版本开始支持)
Sentinel提供了两种限流模式
- route维度:即在Spring配置文件中配置的路由条目,资源名为对应的routeId
- 自定义API维度:用户可以利用Sentinel提供的API来自定义一些API分组
2、路由维度限流
引入POM:
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-spring-cloud-gateway-adapter</artifactId>
</dependency>
yaml配置:
spring:
cloud:
gateway:
routes:
- id: user-service # 路由id
uri: lb://user-service # 跳转服务的uri路径
predicates:
- Path=/user/**
创建GatewayConfiguration 配置文件:
@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;
}
/**
* 初始化一个限流的过滤器
*
* @return
*/
@Bean
@Order(Ordered.HIGHEST_PRECEDENCE)
public GlobalFilter sentinelGatewayFilter() {
return new SentinelGatewayFilter();
}
/**
* 配置限流的异常处理器
*
* @return
*/
@Bean
@Order(Ordered.HIGHEST_PRECEDENCE)
public SentinelGatewayBlockExceptionHandler
sentinelGatewayBlockExceptionHandler() {
return new SentinelGatewayBlockExceptionHandler(viewResolvers,
serverCodecConfigurer);
}
/**
* 加载规则
*/
@PostConstruct
public void doInit() {
initGatewayRules();
}
/**
* 配置初始化的限流参数
*/
public void initGatewayRules() {
Set<GatewayFlowRule> rules = new HashSet<>();
// yaml中配置的路由id
rules.add(new GatewayFlowRule("user-service")
// 限流维度
.setResourceMode(SentinelGatewayConstants.RESOURCE_MODE_ROUTE_ID)
// 限流阈值
.setCount(1)
// 时间窗口
.setIntervalSec(1)
// 正对请求参数进行热点限流
.setParamItem(new GatewayParamFlowItem()
.setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_URL_PARAM)
// 参数名称
.setFieldName("pa")
)
);
GatewayRuleManager.loadRules(rules);
}
}
以上配置表示的限流规则为:当进入到路由ID为user-service
并且请求的URL中拥有一个叫做pa
的参数,在1秒时间内,最大并发数为1。
我们也可以不配置setParamItem()
,那么规则就为:当进入到路由ID为user-service
的所有请求,在1秒时间内,最大并发数为1。
当然setParamItem()
还有很多的限流规则,比如Header参数.
测试:
我们发起请求两个请求,比如:user/list?pa=123
与user/list
,通过快速刷新浏览器模拟并发。
结论:存在pa
参数的请求,连续访问会出现Sentinel
限流,而不带pa
参数的请求,则不会触发。
3、API维度限流
提供了更细化的限流匹配机制,可以针对某些请求实现限流。
引入POM:
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-spring-cloud-gateway-adapter</artifactId>
</dependency>
yaml配置:
spring:
cloud:
gateway:
routes:
- id: user-service # 路由id
uri: lb://user-service # 跳转服务的uri路径
predicates:
- Path=/user/**
- id: wage-service # 路由id
uri: lb://wage-service # 跳转服务的uri路径
predicates:
- Path=/wage/**
创建GatewayConfiguration 配置文件:
@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;
}
/**
* 初始化一个限流的过滤器
*
* @return
*/
@Bean
@Order(Ordered.HIGHEST_PRECEDENCE)
public GlobalFilter sentinelGatewayFilter() {
return new SentinelGatewayFilter();
}
/**
* 配置限流的异常处理器
*
* @return
*/
@Bean
@Order(Ordered.HIGHEST_PRECEDENCE)
public SentinelGatewayBlockExceptionHandler
sentinelGatewayBlockExceptionHandler() {
return new SentinelGatewayBlockExceptionHandler(viewResolvers,
serverCodecConfigurer);
}
/**
* 加载规则
*/
@PostConstruct
public void doInit() {
initCustomizedApis();
initGatewayRules();
}
/**
* 自定义API分组
*/
private void initCustomizedApis() {
Set<ApiDefinition> definitions = new HashSet<>();
//设置分组名称,new GatewayFlowRule()中分组名称一致
ApiDefinition api1 = new ApiDefinition("user-service-api")
.setPredicateItems(new HashSet<ApiPredicateItem>() {{
//设置规则
//以/user 开头的请求
add(new ApiPathPredicateItem().setPattern("/user/list/**").
setMatchStrategy(SentinelGatewayConstants.URL_MATCH_STRATEGY_PREFIX));
//全路径匹配
add(new ApiPathPredicateItem().setPattern("/user/role"));
}});
ApiDefinition api2 = new ApiDefinition("wage-service-api")
.setPredicateItems(new HashSet<ApiPredicateItem>() {{
add(new ApiPathPredicateItem().setPattern("/wage/**").
setMatchStrategy(SentinelGatewayConstants.URL_MATCH_STRATEGY_PREFIX));
}});
definitions.add(api1);
definitions.add(api2);
GatewayApiDefinitionManager.loadApiDefinitions(definitions);
}
/**
* 配置初始化的限流参数
*/
public void initGatewayRules() {
Set<GatewayFlowRule> rules = new HashSet<>();
// 设置api分组名称,名称任意
rules.add(new GatewayFlowRule("user-service-api")
.setResourceMode(SentinelGatewayConstants.RESOURCE_MODE_CUSTOM_API_NAME)
// 限流阈值
.setCount(1)
// 时间窗口
.setIntervalSec(1)
);
// 设置api分组名称,名称任意
rules.add(new GatewayFlowRule("wage-service-api")
.setResourceMode(SentinelGatewayConstants.RESOURCE_MODE_CUSTOM_API_NAME)
// 限流阈值
.setCount(2)
// 时间窗口
.setIntervalSec(1)
);
GatewayRuleManager.loadRules(rules);
}
}
以上配置表示的限流规则为:
-
当请求为
/wage/**
开头的请求会触发wage-service-api
限流规则,在1秒时间内,最大并发数为2。 -
当请求为
/user/list/**
开头和/user/role
的请求会触发user-service-api
限流规则,在1秒时间内,最大并发数为1。
测试:
4、综合使用
我们可以将,路由维度
与API维度
的限流同时进行使用,配置如下:
@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;
}
/**
* 初始化一个限流的过滤器
*
* @return
*/
@Bean
@Order(Ordered.HIGHEST_PRECEDENCE)
public GlobalFilter sentinelGatewayFilter() {
return new SentinelGatewayFilter();
}
/**
* 配置限流的异常处理器
*
* @return
*/
@Bean
@Order(Ordered.HIGHEST_PRECEDENCE)
public SentinelGatewayBlockExceptionHandler
sentinelGatewayBlockExceptionHandler() {
return new SentinelGatewayBlockExceptionHandler(viewResolvers,
serverCodecConfigurer);
}
/**
* 加载规则
*/
@PostConstruct
public void doInit() {
initCustomizedApis();
initGatewayRules();
}
/**
* 自定义API分组
*/
private void initCustomizedApis() {
Set<ApiDefinition> definitions = new HashSet<>();
//设置分组名称,new GatewayFlowRule()中分组名称一致
ApiDefinition api1 = new ApiDefinition("user-service-api")
.setPredicateItems(new HashSet<ApiPredicateItem>() {{
//设置规则
//以/user 开头的请求
add(new ApiPathPredicateItem().setPattern("/user/list/**").
setMatchStrategy(SentinelGatewayConstants.URL_MATCH_STRATEGY_PREFIX));
//全路径匹配
add(new ApiPathPredicateItem().setPattern("/user/role"));
}});
definitions.add(api1);
GatewayApiDefinitionManager.loadApiDefinitions(definitions);
}
/**
* 配置初始化的限流参数
*/
public void initGatewayRules() {
Set<GatewayFlowRule> rules = new HashSet<>();
// 设置路由维度的限流
rules.add(new GatewayFlowRule("user-service")
.setResourceMode(SentinelGatewayConstants.RESOURCE_MODE_ROUTE_ID)
// 限流阈值
.setCount(10)
// 时间窗口
.setIntervalSec(1)
);
// 设置api分组名称,名称任意
rules.add(new GatewayFlowRule("user-service-api")
.setResourceMode(SentinelGatewayConstants.RESOURCE_MODE_CUSTOM_API_NAME)
// 限流阈值
.setCount(1)
// 时间窗口
.setIntervalSec(1)
);
GatewayRuleManager.loadRules(rules);
}
}
以上配置表示的限流规则为:
-
当请求以
user/**
开头的请求,会进入到路由ID为user-service
,并且触发路由维度
的限流规则,在1秒时间内,最大并发数为10。 -
当请求为
/user/list/**
开头和/user/role
的请求会触发user-service-api
限流规则,在1秒时间内,最大并发数为1。
如果同时配置了路由维度
和API维度
的限流规则,那么会优先触发API维度
的限流规则。
测试: