热点参数限流
要使用热点参数限流功能,需要引入以下依赖:
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-parameter-flow-control</artifactId>
<version>x.y.z</version>
</dependency>
如果使用了 spring-cloud-starter-alibaba-sentinel ,可以不用手动引用。
热点参数规则
热点参数规则对象为 ParamFlowRule 类似于流量控制规则对象 FlowRule ,其字段如下:
/**
* 限流阈值类型
* QPS(RuleConstant.FLOW_GRADE_QPS值为1)
* 线程数(RuleConstant.FLOW_GRADE_THREAD值为0)
* 默认为1
*/
private int grade = RuleConstant.FLOW_GRADE_QPS;
/**
* 热点参数的索引,必填,对应 SphU.entry(xxx, args) 中的参数索引位置
*/
private Integer paramIdx;
/**
* 限流阈值
*/
private double count;
/**
* 流控效果(支持快速失败和匀速排队模式) —— 同流量控制配置一致,此处不做详细说明
*/
private int controlBehavior = RuleConstant.CONTROL_BEHAVIOR_DEFAULT;
/**
* 最大排队等待时长(仅在匀速排队模式生效)
*/
private int maxQueueingTimeMs = 0;
/**
* 统计窗口时间长度(单位为秒)
*/
private long durationInSec = 1;
/**
* 参数例外项,可以针对指定的参数值单独设置限流阈值,不受前面 count 阈值的限制。仅支持基本类型和字符串类型
*/
private List<ParamFlowItem> paramFlowItemList = new ArrayList<ParamFlowItem>();
/**
* 是否是集群参数流控规则
*/
private boolean clusterMode = false;
/**
* 集群流控相关配置
*/
private ParamFlowClusterConfig clusterConfig;
ParamFlowRule 大部分都配置都与 FlowRule 一致,包括集群的配置也是一样的。
热点限流动态数据源
ReadableDataSource<String, List<ParamFlowRule>> paramFlowRuleDs = new NacosDataSource<>(nacosPro, GROUP_ID, DATA_ID,
source -> JsonUtil.toGenericBean(source, new TypeReference<List<ParamFlowRule>>(){}));
ParamFlowRuleManager.register2Property(paramFlowRuleDs.getProperty());
同样道理,Spring Cloud的下可以通过 application.yaml 配置进行动态数据源的配置,配置的 rule-type 为:param-flow
来源访问控制
需要根据调用方来限制资源是否通过,这时候可以使用 Sentinel 的黑白名单控制的功能。黑白名单根据资源的请求来源(origin)限制资源是否通过,若配置白名单则只有请求来源位于白名单内时才可通过;若配置黑名单则请求来源位于黑名单时不通过,其余的请求通过。
调用方信息通过 ContextUtil.enter(resourceName, origin) 方法中的 origin 参数传入。
注意:origin 是为了区分请求来源,并不一定是 origin 请求头。此处的 origin 需要我们手动定义(比如定义为来源IP、用户或者来源应用名称等),然后按规则配置。
Spring Cloud Alibaba 下的 origin 定义
Spring Boot / Spring Cloud 下自动扫描的资源,我们要为其定义 origin ,需要实现 RequestOriginParser 接口。默认情况下改接口的实现为空。
import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.RequestOriginParser;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
@Component // 需要实现注册到 Spring 容器
public class MyRequestOriginParser implements RequestOriginParser {
@Override
public String parseOrigin(HttpServletRequest request) {
// 此处只为提供一个示例,实际情况下请自定义获取ip的方法(考虑Apache或nginx代理等情况)
String ip = request.getRemoteAddr();
return ip;
}
}
具体的实现逻辑,我们将在后面的源码分析文章中详细说明,此处就不再详细解析了。
规则配置
黑白名单规则(AuthorityRule)非常简单,主要有以下配置项:
- resource:资源名,即限流规则的作用对象
- limitApp:对应的黑名单/白名单,不同 origin 用 , 分隔,如 appA,appB
- strategy:限制模式,RuleConstant.AUTHORITY_WHITE 为白名单模式,RuleConstant.AUTHORITY_BLACK 为黑名单模式,默认为白名单模式
规则动态数据源配置
ReadableDataSource<String, List<AuthorityRule>> authorityRuleDs = new NacosDataSource<>(nacosPro, GROUP_ID, DATA_ID,
source -> JsonUtil.toGenericBean(source, new TypeReference<List<AuthorityRule>>(){}));
AuthorityRuleManager.register2Property(authorityRuleDs.getProperty());
同样道理,Spring Cloud的下可以通过 application.yaml 配置进行动态数据源的配置,配置的 rule-type 为:authority