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,则结束熔断状态后仍可能再进入熔断状态