Sentinel 限流,降级配置

application.yml关于sentinel配置部分

spring:
  cloud:
    sentinel:
      eager: true
      transport:
        dashboard: localhost:8080
      datasource:
        ds1:
          file:
            rule-type: flow
            data-type: json
            file: 
              classpath:flowrule.json
        ds2:
          file:
            rule-type: degrade
            data-type: json
            file: 
              classpath:degraderule.json

flowrule.json

[
	{
		"resource": "test",
		"controlBehavior": 0,
		"count": 2,
		"grade": 1,
		"limitApp": "default",
		"strategy": 0
	}
]

degraderule.json

[
	{
		"resource": "test1",
		"grade": 0,
		"count": 20.0,
		"timeWindow": 60
	}
]

Controller.java

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;

@RestController
@EnableDiscoveryClient
@SpringBootApplication
public class Application {

	public static void main(String[] args) {
		SpringApplication.run(Application.class, args);
	}

	@SentinelResource(value = "test", blockHandler = "flowException")
	@RequestMapping("test")
	public String test() {
		return "Hello I'm nacos_provide flow";
	}

	@SentinelResource(value = "test1", blockHandler = "degradeException")
	@RequestMapping("test1")
	public String test1() {
		try {
			Thread.sleep(25);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return "Hello I'm nacos_provide degrade";
	}

    // 自定义异常必须与原方法返回值及参数完全一致
	public String flowException(BlockException e) {
		return "限流了!";
	}

    // 自定义异常必须与原方法返回值及参数完全一致
	public String degradeException(BlockException e) {
		return "降级了!";
	}

}

降级策略

  • 平均响应时间 (DEGRADE_GRADE_RT):当 1s 内持续进入 5 个请求,对应时刻的平均响应时间(秒级)均超过阈值(count,以 ms 为单位),那么在接下的时间窗口(DegradeRule 中的 timeWindow,以 s 为单位)之内,对这个方法的调用都会自动地熔断(抛出 DegradeException)。注意 Sentinel 默认统计的 RT 上限是 4900 ms,超出此阈值的都会算作 4900 ms,若需要变更此上限可以通过启动配置项 -Dcsp.sentinel.statistic.max.rt=xxx 来配置
  • 异常比例 (DEGRADE_GRADE_EXCEPTION_RATIO):当资源的每秒请求量 >= 5,并且每秒异常总数占通过量的比值超过阈值(DegradeRule 中的 count)之后,资源进入降级状态,即在接下的时间窗口(DegradeRule 中的 timeWindow,以 s 为单位)之内,对这个方法的调用都会自动地返回。异常比率的阈值范围是 [0.0, 1.0],代表 0% - 100%
  • 异常数 (DEGRADE_GRADE_EXCEPTION_COUNT):当资源近 1 分钟的异常数目超过阈值之后会进行熔断。注意由于统计时间窗口是分钟级别的,若 timeWindow 小于 60s,则结束熔断状态后仍可能再进入熔断状态
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值