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