简单的sentinel 限流例子

  • Post author:
  • Post category:其他

api接口的限流可以只引入阿里的sentinel jar包

导入sentinel 的jar

<dependency>
    <groupId>com.alibaba.csp</groupId>
    <artifactId>sentinel-core</artifactId>
    <version>X.X.X</version>
</dependency>

资源

实现

  1. 针对api接口的限流,可以将接口url作为限流的资源。
  2. 实现接口HandlerInterceptor,通过在拦截器中定义资源。在业务处理器处理请求之前被调用,从而达到在未执行业务代码之前对api接口进行限流。

附上代码

@Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o)
        throws Exception {
        String url = httpServletRequest.getRequestURI();
        if (StringUtils.isBlank(url)) {
            return true;
        }
        Entry urlEntry = null;
        try {
            ContextUtil.enter(url);
            //将url作为资源
            urlEntry = SphU.entry(url);
            return true;
        } catch (BlockException ex) {
        	//资源访问阻止后的处理
            throw ServiceException.getInstance(ResponseCode.EXCEPTION, "请稍后再试");
        } finally {
            if (urlEntry != null) {
                urlEntry.exit();
            }
            ContextUtil.exit();
        }
    }

  1. 针对资源被访问限制后的处理,可以针对不同的url抛出不同异常。
  2. 通过实现HandlerExceptionResolver接口,捕获抛出的异常

规则

规则的配置可以在项目配置,也可以通过采用动态配置,下面代码为了演示设置规则,就最简单定义一个字符串,最优的方法是使用外部数据源,进行动态配置,可以参考sentinel官方文档。

附上代码

    private void parseRuleFromProperty() {
    	private String sentinelFlowRules="XXXXXXX";
        List<ConfigFlowRule> flowRules = JSONArray.parseArray(sentinelFlowRules, ConfigFlowRule.class);
        if (CollectionUtils.isNotEmpty(flowRules)) {
            List<FlowRule> rules = new ArrayList<>();
            flowRules.forEach(e -> {
                FlowRule rule = new FlowRule(e.getValue());
                rule.setCount(e.getCount());
                rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
                rule.setLimitApp("default");
                rules.add(rule);
            });
            FlowRuleManager.loadRules(rules);
        }

    }
  1. 上述代码中,将规则通过一个json数组字符串,json中的key主要包括资源(url地址)、count(qps)。可以自行配置不同的限流规则属性。
  2. FlowRule类表示限流规则
  3. 将定义的规则通过FlowRuleManager.loadRules 加载到内存中

版权声明:本文为wantmiss原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。