使用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)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Nacos 可以与 Sentinel 集成,以实现动态的流量控制和熔断降级策略。这样,你可以使用 Nacos 配置中心来配置 Sentinel 规则,实现对应用程序的实时流量控制和熔断降级。 以下是集成 NacosSentinel 的基本步骤: 1. 首先,你需要在应用程序中引入 NacosSentinel 的客户端库。根据你使用的编程语言和框架,可能需要添加相应的依赖或库文件。 2. 在 Nacos 配置中心中创建配置项,用于存储 Sentinel规则配置。可以在 Nacos 控制台中手动创建或使用 API 自动创建。 3. 在应用程序中使用 Nacos 的配置读取 API,读取 Sentinel 规则配置。这些规则可以是流量控制规则、熔断降级规则等。 4. 将读取到的规则配置传递给 Sentinel 客户端,使其生效。这样,Sentinel 就会根据配置的规则对流量进行控制和熔断降级。 5. 在 Nacos 配置中心中更新规则配置时,应用程序会自动获取最新的配置,并且 Sentinel 会根据新的配置进行动态调整。 下面是一个示例伪代码,展示了如何集成 NacosSentinel: ```python import nacos import sentinel # 创建 Nacos 客户端实例 client = nacos.NacosClient(server_addresses='nacos-server:8848') # 从 Nacos 获取 Sentinel 规则配置 config = client.get_config(data_id='sentinel-rules', group='your-group') # 将规则配置传递给 Sentinel 客户端 sentinel.load_rules(config) # 应用程序主逻辑 def main(): # 执行应用程序逻辑 do_something() if __name__ == '__main__': main() ``` 在上面的示例中,`client.get_config()` 方法用于从 Nacos 中获取 Sentinel 规则配置。然后,通过 `sentinel.load_rules()` 方法将规则配置传递给 Sentinel 客户端。 通过上述步骤,你可以实现 NacosSentinel 的集成,实现动态的流量控制和熔断降级策略。在 Nacos 配置中心更新规则配置时,应用程序会自动获取最新的配置,并且 Sentinel 会根据新的配置进行动态调整。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值