当前位置: 首页 > news >正文

聊聊sentinel的DegradeSlot

本文主要研究一下sentinel的DegradeSlot

DegradeSlot

com/alibaba/csp/sentinel/slots/block/degrade/DegradeSlot.java

public class DegradeSlot extends AbstractLinkedProcessorSlot<DefaultNode> {

    @Override
    public void entry(Context context, ResourceWrapper resourceWrapper, DefaultNode node, int count, Object... args)
        throws Throwable {
        DegradeRuleManager.checkDegrade(resourceWrapper, context, node, count);
        fireEntry(context, resourceWrapper, node, count, args);
    }

    @Override
    public void exit(Context context, ResourceWrapper resourceWrapper, int count, Object... args) {
        fireExit(context, resourceWrapper, count, args);
    }
}
  • 调用DegradeRuleManager.checkDegrade进行降级规则检测

DegradeRuleManager

com/alibaba/csp/sentinel/slots/block/degrade/DegradeRuleManager.java

public class DegradeRuleManager {

    private static volatile Map<String, List<DegradeRule>> degradeRules
        = new ConcurrentHashMap<String, List<DegradeRule>>();

    final static RulePropertyListener listener = new RulePropertyListener();
    private static SentinelProperty<List<DegradeRule>> currentProperty
        = new DynamicSentinelProperty<List<DegradeRule>>();

    static {
        currentProperty.addListener(listener);
    }

    /**
     * Listen to the {@link SentinelProperty} for {@link DegradeRule}s. The property is the source
     * of {@link DegradeRule}s. Degrade rules can also be set by {@link #loadRules(List)} directly.
     *
     * @param property the property to listen.
     */
    public static void register2Property(SentinelProperty<List<DegradeRule>> property) {
        synchronized (listener) {
            currentProperty.removeListener(listener);
            property.addListener(listener);
            currentProperty = property;
        }
    }

    public static void checkDegrade(ResourceWrapper resource, Context context, DefaultNode node, int count)
        throws BlockException {
        if (degradeRules == null) {
            return;
        }

        List<DegradeRule> rules = degradeRules.get(resource.getName());
        if (rules == null) {
            return;
        }

        for (DegradeRule rule : rules) {
            if (!rule.passCheck(context, node, count)) {
                throw new DegradeException(rule.getLimitApp());
            }
        }
    }

    //......
}
  • checkDegrade根据资源名称获取对应的降级规则,然后挨个遍历检查

DegradeRule

com/alibaba/csp/sentinel/slots/block/degrade/DegradeRule.java

/**
 * <p>
 * Degrade is used when the resources are in an unstable state, these resources
 * will be degraded within the next defined time window. There are two ways to
 * measure whether a resource is stable or not:
 * </p>
 * <ul>
 * <li>
 * Average response time ({@code DEGRADE_GRADE_RT}): When
 * the average RT exceeds the threshold ('count' in 'DegradeRule', in milliseconds), the
 * resource enters a quasi-degraded state. If the RT of next coming 5
 * requests still exceed this threshold, this resource will be downgraded, which
 * means that in the next time window (defined in 'timeWindow', in seconds) all the
 * access to this resource will be blocked.
 * </li>
 * <li>
 * Exception ratio: When the ratio of exception count per second and the
 * success qps exceeds the threshold, access to the resource will be blocked in
 * the coming window.
 * </li>
 * </ul>
 *
 * @author jialiang.linjl
 */
public class DegradeRule extends AbstractRule {

    private static final int RT_MAX_EXCEED_N = 5;

    private static ScheduledExecutorService pool = Executors.newScheduledThreadPool(
        Runtime.getRuntime().availableProcessors(), new NamedThreadFactory("sentinel-degrade-reset-task", true));

    /**
     * RT threshold or exception ratio threshold count.
     */
    private double count;

    /**
     * Degrade recover timeout (in seconds) when degradation occurs.
     */
    private int timeWindow;

    /**
     * Degrade strategy (0: average RT, 1: exception ratio).
     */
    private int grade = RuleConstant.DEGRADE_GRADE_RT;

    private volatile boolean cut = false;

    public int getGrade() {
        return grade;
    }

    public void setGrade(int grade) {
        this.grade = grade;
    }

    private AtomicLong passCount = new AtomicLong(0);

    private final Object lock = new Object();

    //......

    @Override
    public boolean passCheck(Context context, DefaultNode node, int acquireCount, Object... args) {

        if (cut) {
            return false;
        }

        ClusterNode clusterNode = ClusterBuilderSlot.getClusterNode(this.getResource());
        if (clusterNode == null) {
            return true;
        }

        if (grade == RuleConstant.DEGRADE_GRADE_RT) {
            double rt = clusterNode.avgRt();
            if (rt < this.count) {
                passCount.set(0);
                return true;
            }

            // Sentinel will degrade the service only if count exceeds.
            if (passCount.incrementAndGet() < RT_MAX_EXCEED_N) {
                return true;
            }
        } else {
            double exception = clusterNode.exceptionQps();
            double success = clusterNode.successQps();
            long total = clusterNode.totalQps();
            // if total qps less than RT_MAX_EXCEED_N, pass.
            if (total < RT_MAX_EXCEED_N) {
                return true;
            }

            if (success == 0) {
                return exception < RT_MAX_EXCEED_N;
            }

            if (exception / (success + exception) < count) {
                return true;
            }
        }

        synchronized (lock) {
            if (!cut) {
                // Automatically degrade.
                cut = true;
                ResetTask resetTask = new ResetTask(this);
                pool.schedule(resetTask, timeWindow, TimeUnit.SECONDS);
            }

            return false;
        }
    }

    //......

    private static final class ResetTask implements Runnable {

        private DegradeRule rule;

        ResetTask(DegradeRule rule) {
            this.rule = rule;
        }

        @Override
        public void run() {
            rule.getPassCount().set(0);
            rule.setCut(false);
        }
    }
}
  • 这个passCheck根据平均响应时间以及异常个数等进行降级判断
  • 触发降级时标志cut为true,然后启动一个ResetTask,在指定时间窗口之后重置cut为false并清空passCount计数

小结

sentinel的DegradeSlot主要依据平均响应时间以及异常次数来判断,进入降级模式时启动定时任务在指定时间窗口重置相关计数,恢复到正常模式。

doc

  • DegradeSlot

相关文章:

  • 前端UI框架选择区别对比推荐
  • 解压缩软件居然还有多种工作模式!长见识了
  • 小白科普:分布式和集群
  • dubbo与springcloud初识
  • Android 5.1 预制输入法
  • Python游戏《外星人入侵》来了~
  • win10装双系统图文教程
  • 第10章神经网络基础
  • MpVue 致力打造H5与小程序的代码共用
  • 参加2018之江杯全球人工智能大赛 :视频识别问答(三)
  • 解决加载模型预测数据时报错的问题
  • java 颠倒整数
  • 【火炉炼AI】机器学习022-使用均值漂移聚类算法构建模型
  • Python从菜鸟到高手(5):数字
  • python中的None
  • ECS应用管理最佳实践
  • Git 使用集
  • Java 11 发布计划来了,已确定 3个 新特性!!
  • Java,console输出实时的转向GUI textbox
  • Java多线程(4):使用线程池执行定时任务
  • laravel 用artisan创建自己的模板
  • Mac转Windows的拯救指南
  • React-Native - 收藏集 - 掘金
  • spring + angular 实现导出excel
  • use Google search engine
  • Vue源码解析(二)Vue的双向绑定讲解及实现
  • WordPress 获取当前文章下的所有附件/获取指定ID文章的附件(图片、文件、视频)...
  • 翻译:Hystrix - How To Use
  • 基于axios的vue插件,让http请求更简单
  • 浅谈Golang中select的用法
  • 如何实现 font-size 的响应式
  • 如何在 Tornado 中实现 Middleware
  • 我感觉这是史上最牛的防sql注入方法类
  • 无服务器化是企业 IT 架构的未来吗?
  • ​ArcGIS Pro 如何批量删除字段
  • ​香农与信息论三大定律
  • ###51单片机学习(2)-----如何通过C语言运用延时函数设计LED流水灯
  • #define
  • #NOIP 2014#day.2 T1 无限网络发射器选址
  • #stm32整理(一)flash读写
  • #基础#使用Jupyter进行Notebook的转换 .ipynb文件导出为.md文件
  • #我与虚拟机的故事#连载20:周志明虚拟机第 3 版:到底值不值得买?
  • (02)Cartographer源码无死角解析-(03) 新数据运行与地图保存、加载地图启动仅定位模式
  • (MIT博士)林达华老师-概率模型与计算机视觉”
  • (第二周)效能测试
  • (动手学习深度学习)第13章 计算机视觉---微调
  • (翻译)Quartz官方教程——第一课:Quartz入门
  • (简单) HDU 2612 Find a way,BFS。
  • (十八)三元表达式和列表解析
  • (一)pytest自动化测试框架之生成测试报告(mac系统)
  • (原创)攻击方式学习之(4) - 拒绝服务(DOS/DDOS/DRDOS)
  • (转)人的集合论——移山之道
  • .gitignore
  • .Net - 类的介绍
  • .NET 4.0中使用内存映射文件实现进程通讯