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源碼鏈接

 

  

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章