开发者学堂课程【精通 Spring Cloud Alibaba:Sentinel 手动实现限流规则】学习笔记,与课程紧密联系,让用户快速学习知识。
课程地址:https://developer.aliyun.com/learning/course/634/detail/10137
Sentinel 手动实现限流规则
限流配置有两种方案:
1. 手动使用代码配置 纯代码/注解的形式
2. Sentinel 控制台形式配置
3. 默认情况下 Sentinel 不对数据持久化,需要自己独立持久化。
实现的步骤:
创建我们的流控规则/限流规则,然后再被映射地址去引用。
@Reques tMapping(" /orderToMember")
public String orderToMember() {
return "orderToMember";
}
代码:
//限流规则名称
private static final String GETORDER_ KEY =
‘’getOrder” ;
@RequestMapping( "/orderFeignToMember")
public String orderFeignToMember() {
String result = memberServiceFeign. getUser( userld: 1);
return "我是订单服务调用会员服务的接口,返回结果" + result;
}
@RequestMapping("/")
public String order()
{ return "订单服务"; }
@Reques tMapping( "/orderToMember"){
Entry entry = nu11;
try{
entry = SphU. entry(GETORDER_ KEY);
return
“orderToMember
接口”
}catch (Exception e){
//限流的情况就会进入到 Exception
return
“当前访问人数过多,请稍后重试!”
} finally {
//SphU.entry(xxx)需要与 entryexit()成对出现否则会导致调用链记录异常
if (entry != null){
entry.exit();
}
}
}
//创建我们的限流规则
public String initFlowQpsRule() {
List<FlowRule> rules = new ArrayList<FlowRule>();
FlowRule rule1 = new F1owRule();
rule1. setResource( GETORDER_ KEY);
// QPS 控制在1,资源名称
rule1. setCount(1);
// QPS 限流
rule1. setGrade(RuleConstant. FLOW_ GRADE_ QPS);
rule1. setLimitApp("default" );
rules .add(rule1);
//默认限流名称数
FlowRu1eManager . LoadRules(rules);
return
“....限流配置初始化成功....”
}
}
@RequestMapping("/initFlowQpsRule")
public String initFlowQpsRule() {
List<FlowRule> rules = new ArrayList<FlowRule>();FlowRule rule1=newFlowRule();rule1.setResource(GETORDER_KEY);
//QPS 控制在2以内
rule1.setCount(1);
//QPS 限流
rule1.setGrade(RuleConstant.FLOW_GRADE_QPS); rule1.setLimitApp("default");
rules.add(rule1);
FlowRuleManager.loadRules(rules);
return
"....限流配置初始化成功..";
}
以上代码需要依赖的配置:(放入到项目当中)
<dependency> roupId>ore. sprineframework.c loud</groupId> <artifactId>spring-c loud-salibaba- sent inel</artifactId>+ <version>0.2.2. REL EASE</version>+ </dependency> <dependency> <groupId>org.springfranework.boot</gcoupd> <artifactId>spring- boot - starter- actuator</ artifactId>: </dependency> |
先去加载匹配到规则,把规则初始化内置里面,初始化完成后再刷新。
要想每秒钟最多有10个请求访问,把 rule1. setCount(1);
// QPS 限流 改为 rule1. setCount(10);