聊聊sentinel的ModifyRulesCommandHandler

本文主要研究一下sentinel的ModifyRulesCommandHandler

ModifyRulesCommandHandler

sentinel-transport-common-0.1.1-sources.jar!/com/alibaba/csp/sentinel/command/handler/ModifyRulesCommandHandler.java

@CommandMapping(name = "setRules")
public class ModifyRulesCommandHandler implements CommandHandler<String> {

    static DataSource<?, List<FlowRule>> flowDataSource = null;
    static DataSource<?, List<AuthorityRule>> authorityDataSource = null;
    static DataSource<?, List<DegradeRule>> degradeDataSource = null;
    static DataSource<?, List<SystemRule>> systemSource = null;

    public static synchronized void registerFlowDataSource(DataSource<?, List<FlowRule>> datasource) {
        flowDataSource = datasource;
    }

    public static synchronized void registerAuthorityDataSource(DataSource<?, List<AuthorityRule>> dataSource) {
        authorityDataSource = dataSource;
    }

    public static synchronized void registerDegradeDataSource(DataSource<?, List<DegradeRule>> dataSource) {
        degradeDataSource = dataSource;
    }

    public static synchronized void registerSystemDataSource(DataSource<?, List<SystemRule>> dataSource) {
        systemSource = dataSource;
    }

    @Override
    public CommandResponse<String> handle(CommandRequest request) {
        String type = request.getParam("type");
        // rule data in get parameter
        String data = request.getParam("data");
        if (StringUtil.isNotEmpty(data)) {
            try {
                data = URLDecoder.decode(data, "utf-8");
            } catch (Exception e) {
                RecordLog.info("decode rule data error", e);
                return CommandResponse.ofFailure(e, "decode rule data error");
            }
        }

        RecordLog.info("receive rule change:" + type);
        RecordLog.info(data);

        String result = "success";

        if ("flow".equalsIgnoreCase(type)) {
            List<FlowRule> flowRules = JSONArray.parseArray(data, FlowRule.class);
            FlowRuleManager.loadRules(flowRules);
            if (flowDataSource != null) {
                try {
                    flowDataSource.writeDataSource(flowRules);
                } catch (Exception e) {
                    result = "partial success";
                    RecordLog.info(e.getMessage(), e);
                }
            }
            return CommandResponse.ofSuccess(result);
        } else if ("authority".equalsIgnoreCase(type)) {
            List<AuthorityRule> rules = JSONArray.parseArray(data, AuthorityRule.class);
            AuthorityRuleManager.loadRules(rules);
            if (authorityDataSource != null) {
                try {
                    authorityDataSource.writeDataSource(rules);
                } catch (Exception e) {
                    result = "partial success";
                    RecordLog.info(e.getMessage(), e);
                }
            }
            return CommandResponse.ofSuccess(result);
        } else if ("degrade".equalsIgnoreCase(type)) {
            List<DegradeRule> rules = JSONArray.parseArray(data, DegradeRule.class);
            DegradeRuleManager.loadRules(rules);
            if (degradeDataSource != null) {
                try {
                    degradeDataSource.writeDataSource(rules);
                } catch (Exception e) {
                    result = "partial success";
                    RecordLog.info(e.getMessage(), e);
                }
            }
            return CommandResponse.ofSuccess(result);
        } else if ("system".equalsIgnoreCase(type)) {
            List<SystemRule> rules = JSONArray.parseArray(data, SystemRule.class);
            SystemRuleManager.loadRules(rules);
            if (systemSource != null) {
                try {
                    systemSource.writeDataSource(rules);
                } catch (Exception e) {
                    result = "partial success";
                    RecordLog.info(e.getMessage(), e);
                }
            }
            return CommandResponse.ofSuccess(result);
        }
        return CommandResponse.ofFailure(new IllegalArgumentException("invalid type"));

    }

}
  • 如果type是flow的话,则调用FlowRuleManager.loadRules(flowRules);更新

FlowRuleManager

sentinel-core-0.1.1-sources.jar!/com/alibaba/csp/sentinel/slots/block/flow/FlowRuleManager.java

    /**
     * Load {@link FlowRule}s, former rules will be replaced.
     *
     * @param rules new rules to load.
     */
    public static void loadRules(List<FlowRule> rules) {
        currentProperty.updateValue(rules);
    }
  • 调用的是DynamicSentinelProperty的updateValue

DynamicSentinelProperty

sentinel-core-0.1.1-sources.jar!/com/alibaba/csp/sentinel/property/DynamicSentinelProperty.java

    public void updateValue(T newValue) {
        if (isEqual(value, newValue)) {
            return;
        }
        RecordLog.info("SentinelProperty, config is real updated to: " + newValue);

        value = newValue;
        for (PropertyListener<T> listener : listeners) {
            listener.configUpdate(newValue);
        }

    }
  • 这里委托给listeners去进行configUpdate

FlowPropertyListener

sentinel-core-0.1.1-sources.jar!/com/alibaba/csp/sentinel/slots/block/flow/FlowRuleManager.java

    private static final class FlowPropertyListener implements PropertyListener<List<FlowRule>> {

        @Override
        public void configUpdate(List<FlowRule> value) {
            Map<String, List<FlowRule>> rules = loadFlowConf(value);
            if (rules != null) {
                flowRules.clear();
                flowRules.putAll(rules);
            }
            RecordLog.info("receive flow config: " + flowRules);
        }

        @Override
        public void configLoad(List<FlowRule> conf) {
            Map<String, List<FlowRule>> rules = loadFlowConf(conf);
            if (rules != null) {
                flowRules.clear();
                flowRules.putAll(rules);
            }
            RecordLog.info("load flow config: " + flowRules);
        }

    }
  • 这里的configUpdate方法调用loadFlowConf进行加载

FlowRuleManager.loadFlowConf

sentinel-core-0.1.1-sources.jar!/com/alibaba/csp/sentinel/slots/block/flow/FlowRuleManager.java

    private static Map<String, List<FlowRule>> loadFlowConf(List<FlowRule> list) {
        Map<String, List<FlowRule>> newRuleMap = new ConcurrentHashMap<String, List<FlowRule>>();

        if (list == null) {
            return newRuleMap;
        }

        for (FlowRule rule : list) {
            if (StringUtil.isBlank(rule.getLimitApp())) {
                rule.setLimitApp(FlowRule.LIMIT_APP_DEFAULT);
            }

            Controller rater = new DefaultController(rule.getCount(), rule.getGrade());
            if (rule.getGrade() == RuleConstant.FLOW_GRADE_QPS
                && rule.getControlBehavior() == RuleConstant.CONTROL_BEHAVIOR_WARM_UP
                && rule.getWarmUpPeriodSec() > 0) {
                rater = new WarmUpController(rule.getCount(), rule.getWarmUpPeriodSec(), ColdFactorProperty.coldFactor);

            } else if (rule.getGrade() == RuleConstant.FLOW_GRADE_QPS
                && rule.getControlBehavior() == RuleConstant.CONTROL_BEHAVIOR_RATE_LIMITER
                && rule.getMaxQueueingTimeMs() > 0) {
                rater = new PaceController(rule.getMaxQueueingTimeMs(), rule.getCount());
            }
            rule.setRater(rater);

            String identity = rule.getResource();
            List<FlowRule> ruleM = newRuleMap.get(identity);

            if (ruleM == null) {
                ruleM = new ArrayList<FlowRule>();
                newRuleMap.put(identity, ruleM);
            }

            ruleM.add(rule);

        }
        return newRuleMap;
    }
  • 这里主要是设置rater,rater有两种,一种是WarmUpController,另外一种是PaceController

小结

  • 在sentinel的dashboard给指定实例添加限流规则的话,会同步调用实例的sentinel接口,发送setRules指令
  • 应用端接收到setRules指令之后,使用ModifyRulesCommandHandler来处理,具体就是将规则覆盖本地

doc

  • Sentinel工作主流程

原文发布于微信公众号 - 码匠的流水账(geek_luandun)

原文发表时间:2018-08-16

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏小樱的经验随笔

Code forces 719A Vitya in the Countryside

A. Vitya in the Countryside time limit per test:1 second memory limit per test:2...

3436
来自专栏个人分享

Socket与Http方式解析发送xml消息封装中间件jar包

  最近项目代码中太多重复的编写Document,不同的接口需要不同的模板,于是重写提取公共部分打成jar包,方便各个系统统一使用~

1393
来自专栏mukekeheart的iOS之旅

No.009 Palindrome Number

9. Palindrome Number Total Accepted: 136330 Total Submissions: 418995 Difficulty...

2287
来自专栏小樱的经验随笔

Gym 100952D&&2015 HIAST Collegiate Programming Contest D. Time to go back【杨辉三角预处理,组合数,dp】

D. Time to go back time limit per test:1 second memory limit per test:256 megaby...

2876
来自专栏java、Spring、技术分享

深入分析Spring MVC中RequestBody与ResponseBody

  在SpringMVC中,可以使用@RequestBody和@ResponseBody两个注解,分别完成请求报文到对象和对象到响应报文的转换。在Sprin...

2061
来自专栏GIS讲堂

geotools中shp和geojson格式的相互转换

5133
来自专栏开发之途

Android Gson使用详解

2705
来自专栏积累沉淀

Hadoop--HDFS API编程封装

HDFS是一个分布式文件系统,既然是文件系统,就可以对其文件进行操作,比如说新建文件、删除文件、读取文件内容等操作。下面记录一下使用JAVA API对HDFS中...

27710
来自专栏闻道于事

SSM框架整合项目 :投票系统

框架: Spring SpringMVC MyBatis 题目: 投票系统 ? 导包: 1, spring 2, MyBatis 3, mybatis-spri...

8475
来自专栏技术专栏

java程序 如何优雅地读取xml文件

4232

扫码关注云+社区