开发者社区 > 云原生 > 中间件 > 正文

Sentinel 怎么配置和设置,才能使用body的变量限流呢?

Sentinel 怎么配置和设置,才能使用body的变量限流呢?

展开
收起
真的很搞笑 2023-08-02 09:42:26 104 0
1 条回答
写回答
取消 提交回答
  • 北京阿里云ACE会长

    使用 Sentinel 实现基于请求body限流主要步骤如下:

    添加 Sentinel 依赖:
    xml
    Copy


    com.alibaba.csp
    sentinel-core
    最新的版本

    实现自定义资源读取器 FlowRuleLoader
    java
    Copy
    public class BodyRequestParamFlowRuleLoader implements FlowRuleLoader {

    @Override
    public List<FlowRule> loadRules() {
        // 解析body提取需要限流的参数
        // ...
        List<FlowRule> rules = new ArrayList<>();
        // ...
        return rules;
    }
    

    }
    在 Sentinel 控制台或代码中注册自定义资源读取器
    java
    Copy
    // 控制台方式
    BodyRequestParamFlowRuleLoader ruleLoader = new BodyRequestParamFlowRuleLoader();
    SentinelAPI.registerFlowRuleLoader(ruleLoader);

    // 代码方式
    FlowRuleManager.register2Property(ruleLoader.loadRules());
    在被保护的资源处,提取 body 中需要限流的参数
    java
    Copy
    @SentinelResource(value = "resource", blockHandler = "handleException")
    public void resource(HttpServletRequest request) {
    String param = getRequestParamFromBody(request);
    // ...
    }

    private String getRequestParamFromBody(HttpServletRequest request) {
    // 解析请求body,提取需要限流的参数
    // ...
    }
    在 BodyRequestParamFlowRuleLoader#loadRules 中根据该参数构建 FlowRule

    2023-08-03 20:03:54
    赞同 展开评论 打赏

为企业提供高效、稳定、易扩展的中间件产品。

热门讨论

热门文章

相关电子书

更多
阿里云容器 AHAS Sentinel 网关流控揭秘 立即下载
workshop专场-微服务专场-开发者动手实践营-微服务-使用Sentinel进行微服务流量控制 立即下载
Sentinel分布式系统下的流量防卫兵 立即下载