使用Nacos和Sentinel设置全局规则
背景
众所周知,Sentinel规则需要作用在资源上才能进行限流和熔断。但大部分情况下,我们会开发众多接口,一个一个去添加资源并绑定规则比较麻烦。偷懒的程序员可能就不去做这件事了,这样我们的服务就没有被保护了。系统规则虽然也能起到一定的保护作用,但如果每个接口都有默认的规则会更好。本博客解决这个问题。
原理
1.Nacos的ConfigService可以添加监听器,当配置变化后,会推送到客户端,可做全局默认实现.全局规则不指定资源
2.不管个性化还是全局规则变化,均重新加载所有资源
3.为保证全局规则刷新不影响个性化规则,需保证以个性化规则为主
实现
定制系统资源
package com.zasd.third.api.sentinel.resource;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.HashSet;
import java.util.Set;
/**
* @description 存放sentinel资源
* @author konglcwqy
* @date 2022/10/14 14:45
*/
public class SentinelResourceConstant {
/**
* 功能描述:获取所有资源
* @author konglcwqy
* @date 2022/10/21 15:19
* @param
* @return java.util.Set<java.lang.String>
*/
public static Set<String> getAllResource() throws Exception {
Set<String> resource = new HashSet<String>();
Field[] fields = SentinelResourceConstant.class.getDeclaredFields();
int modifiers = 0;
boolean flag = false;
for (Field field : fields) {
modifiers = field.getModifiers();
flag = (Modifier.isPublic(modifiers) && Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers));
if(flag){
resource.add(field.get(null).toString());
}
}
return resource;
}
public static final String WELCOME_SERVICE_INDEX = "welcomeIndex";
public static final String MATEA_SERVICE_GETMEMBERCODEINFO = "maTeaGetMemberCodeInfo";
public static final String POLICEDEPARTMENT_SERVICE_HTTPSCONVERT = "PoliceDepartmentHttpsConvert";
public static final String POLICEDEPARTMENT_SERVICE_HTTPSCHECKBLK = "PoliceDepartmentHttpsCheckBlk";
public static final String AUTHENTICATION_SERVICE_PERSONCREDIBILITYV2 = "AuthenticationPersonCredibilityV2";
public static final String AUTHENTICATION_SERVICE_CARDNOANDFACECERTIFICATION = "AuthenticationCardnoAndFaceCertification";
}
定制全局和个性化的配置文件
全局:
{
"degradeRules": [{
"count": 3000.0,
"grade": 0,
"minRequestAmount": 5,
"slowRatioThreshold": 0.2,
"statIntervalMs": 1000,
"timeWindow": 10
}, {
"count": 0.2,
"grade": 1,
"minRequestAmount": 5,
"slowRatioThreshold": 1.0,
"statIntervalMs": 1000,
"timeWindow": 10
}, {
"count": 2.0,
"grade": 2,
"minRequestAmount": 5,
"slowRatioThreshold": 1.0,
"statIntervalMs": 1000,
"timeWindow": 10
}],
"flowRules": [{
"clusterMode": false,
"controlBehavior": 0,
"count": 240.0,
"grade": 1,
"limitApp": "default",
"maxQueueingTimeMs": 500,
"strategy": 0,
"warmUpPeriodSec": 10
}],
"systemRules": [{
"avgRt": 3000,
"highestCpuUsage": 0.8,
"highestSystemLoad": 10.0,
"maxThread": -1,
"qps": 200.0
}]
}
全局对应的实体类
package com.zasd.third.api.config;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.system.SystemRule;
import com.alibaba.fastjson.JSON;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
/**
* @description 全局规则
* @author konglcwqy
* @date 2022/10/21 10:48
*/
@Data
public class GloalRule {
//全局流控规则
private List<FlowRule> flowRules;
//全局降级规则
private List<DegradeRule> degradeRules;
//全局系统规则
private List<SystemRule> systemRules;
public static void main(String[] args) {
GloalRule gloalRule = new GloalRule();
//设置流控规则QPS
List<FlowRule> flowRules = new ArrayList<FlowRule>();
FlowRule flowRule = new FlowRule();
flowRule.setCount(240);
flowRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
flowRule.setLimitApp("default");
flowRule.setStrategy(RuleConstant.STRATEGY_DIRECT);
flowRules.add(flowRule);
//设置熔断规则
List<DegradeRule> degradeRules = new ArrayList<DegradeRule>();
//慢调用:一秒内至少有5次请求,超过3秒响应的为慢调用,如果慢调用次数占总次数的0.2就熔断
DegradeRule degradeGradeRt = new DegradeRule();
degradeGradeRt.setCount(3000);
degradeGradeRt.setGrade(RuleConstant.DEGRADE_GRADE_RT);
degradeGradeRt.setTimeWindow(10);
degradeGradeRt.setMinRequestAmount(5);
degradeGradeRt.setStatIntervalMs(1000);
degradeGradeRt.setSlowRatioThreshold(0.2);
//异常比例
DegradeRule exceptionRatio = new DegradeRule();
exceptionRatio.setCount(0.2);
exceptionRatio.setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_RATIO);
exceptionRatio.setTimeWindow(10);
exceptionRatio.setMinRequestAmount(5);
exceptionRatio.setStatIntervalMs(1000);
//异常数
DegradeRule exceptionNum = new DegradeRule();
exceptionNum.setCount(2);
exceptionNum.setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_COUNT);
exceptionNum.setTimeWindow(10);
exceptionNum.setMinRequestAmount(5);
exceptionNum.setStatIntervalMs(1000);
degradeRules.add(degradeGradeRt);
degradeRules.add(exceptionRatio);
degradeRules.add(exceptionNum);
//设置系统规则
List<SystemRule> systemRules = new ArrayList<SystemRule>();
//cpu 80%
SystemRule systemRule = new SystemRule();
systemRule.setHighestCpuUsage(0.8);
systemRule.setQps(200);
systemRule.setAvgRt(3000);
systemRule.setHighestSystemLoad(10);
systemRules.add(systemRule)