springboot集成Sentinel

1、添加依赖

  • 该版本匹配springboot 2.3.x和2.4.x
<dependency>
	<groupId>com.alibaba.cloud</groupId>
	<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
	<version>2021.1</version>
</dependency>

2、SentinelConfig配置限流规则

@Configuration
public class SentinelConfig {

    @Bean
    public SentinelResourceAspect sentinelResourceAspect() {
        return new SentinelResourceAspect();
    }

    @PostConstruct
    private void initRules() {
        //=============================规则1=========================
        FlowRule rule1 = new FlowRule();
        rule1.setResource("rule1");//规则名称
        rule1.setGrade(RuleConstant.FLOW_GRADE_QPS);//如果设置0则按照线程数限流,如果设置1则按照QPS(每秒查询率)限流
        rule1.setCount(100);   // 每秒调用最大次数为 100 次
        rule1.setControlBehavior(0);//0快速失败,1预警,2排队等候
        rule1.setMaxQueueingTimeMs(1000);//排队超时阈值

        //=============================规则2=========================
        FlowRule rule2 = new FlowRule();
        rule2.setResource("rule2");
        rule2.setGrade(RuleConstant.FLOW_GRADE_QPS);
        rule2.setCount(10);   // 每秒调用最大次数为 10 次

        List<FlowRule> rules = new ArrayList<>();
        rules.add(rule1);
        rules.add(rule2);
        FlowRuleManager.loadRules(rules);
    }
}

3、API限流

@SentinelResource(value = "rule1", blockHandler = "poll", blockHandlerClass = SentinelHandler.class)
@ApiOperation("批量拉取消息")
@PostMapping("/poll")
public BaseResult poll(@RequestBody @Valid PollMessageRequest request){
    return BaseResult.success(kafkaService.poll(request));
}

4、配置handler

  • handler里的方法必须用public static修饰
  • handler里的方法的返回值类型必须和原方法保持一致,参数是在原参数后边加一个BlockException
public class SentinelHandler {

    public static BaseResult poll(PollMessageRequest request, BlockException e) {
        throw new BusinessException("请勿频繁操作");
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值