Springboot限流工具之sentinel单机限流场景无控制台

1. sentinel简介

随着微服务的流行,服务和服务之间的稳定性变得越来越重要。Sentinel 以流量为切入点,从流量控制、熔断降级、系统负载保护等多个维度保护服务的稳定性。

2.包引入和配置

本次方案是不引入控制台的限流应用

maven包的引入

<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>

application.yml加一个qps限制

qps:
  limit:2

  

3.接口限流代码

1.接口代码

@RestController
public class MyController {
    @RequestMapping("/hello")
    @SentinelResource(value = SentinelRuleConfig.QPS_LIMIT)
    public String hello(){
        return "hello";
    }
}

2.单机全局限流配置类SentinelRuleConfig.class

@Component
public class SentinelRuleConfig implements InitializingBean {

    @Value("${qps.limit}")
    private Integer limit;

    public final static String QPS_LIMIT = "concurrent_qps_limit";

    @Override
    public void afterPropertiesSet() {
        initFlowQpsRule(QPS_LIMIT);
    }

    private void initFlowQpsRule(String resource) {
        List<FlowRule> rules = new ArrayList<>();
        FlowRule rule1 = new FlowRule();
        rule1.setResource(resource);
        rule1.setCount(limit);
        rule1.setGrade(RuleConstant.FLOW_GRADE_QPS);
        rules.add(rule1);
        FlowRuleManager.loadRules(rules);
    }
}

3.拒绝策略

支持自定义异常处理通过blockHandler来定义处理类,我采用的是全局异常处理统一返回固定信息

@RestControllerAdvice
public class GlobalExceptionHandler{

    /**
     * 限流异常
     */
    @ExceptionHandler(FlowException.class)
    public Result flowExceptionHandler(FlowException ex) {
        return Result.failed(ex.msg);
    }
}

4.接口限流测试

已经用jemter或者postman等工具手动测试,发现每秒接口并发超过2的时候会返回我们定义的提示信息。

5. 总结

本文介绍的是sentinel的单机使用场景,不支持集群,不需要引入控制台。目前demo中介绍了一种qps限制策略。可以有其它多种策略可用,根据业务需要自行选定。

sentinel源码链接

  

作者:森林木马

-------------------------------------------

特此声明:所有评论和私信都会在第一时间回复。也欢迎朋友们指正错误,共同进步!

如果觉得这篇文章对你有小小的帮助的话,记得在右下角点个“推荐”哦,博主在此感谢!

个性签名:好记性不如勤随笔,好随笔还请多关注!

原文地址:https://www.cnblogs.com/owenma/p/15646850.html