要使用热点参数限流功能,需要引入以下依赖:
com.alibaba.csp sentinel-parameter-flow-control x.y.z
如果使用了 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 paramFlowItemList = new ArrayList();/*** 是否是集群参数流控规则*/private boolean clusterMode = false;/*** 集群流控相关配置*/private ParamFlowClusterConfig clusterConfig;
ParamFlowRule 大部分都配置都与 FlowRule 一致,包括集群的配置也是一样的。
ReadableDataSource> paramFlowRuleDs = new NacosDataSource<>(nacosPro, GROUP_ID, DATA_ID,source -> JsonUtil.toGenericBean(source, new TypeReference>(){}));
ParamFlowRuleManager.register2Property(paramFlowRuleDs.getProperty());
同样道理,Spring Cloud的下可以通过 application.yaml 配置进行动态数据源的配置,配置的 rule-type 为:param-flow
需要根据调用方来限制资源是否通过,这时候可以使用 Sentinel 的黑白名单控制的功能。黑白名单根据资源的请求来源(origin)限制资源是否通过,若配置白名单则只有请求来源位于白名单内时才可通过;若配置黑名单则请求来源位于黑名单时不通过,其余的请求通过。
调用方信息通过 ContextUtil.enter(resourceName, origin) 方法中的 origin 参数传入。
注意:origin 是为了区分请求来源,并不一定是 origin 请求头。此处的 origin 需要我们手动定义(比如定义为来源IP、用户或者来源应用名称等),然后按规则配置。
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 {@Overridepublic String parseOrigin(HttpServletRequest request) {// 此处只为提供一个示例,实际情况下请自定义获取ip的方法(考虑Apache或nginx代理等情况)String ip = request.getRemoteAddr();return ip;}
}
具体的实现逻辑,我们将在后面的源码分析文章中详细说明,此处就不再详细解析了。
黑白名单规则(AuthorityRule)非常简单,主要有以下配置项:
ReadableDataSource> authorityRuleDs = new NacosDataSource<>(nacosPro, GROUP_ID, DATA_ID,source -> JsonUtil.toGenericBean(source, new TypeReference>(){}));
AuthorityRuleManager.register2Property(authorityRuleDs.getProperty());
同样道理,Spring Cloud的下可以通过 application.yaml 配置进行动态数据源的配置,配置的 rule-type 为:authority
上一篇:神经网络基础