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,則結束熔斷狀態後仍可能再進入熔斷狀態