# 简介
为了防止服务雪崩的发生,在发现了对某些资源请求的响应缓慢或调用异常较多时,直接将对这些资源的请求掐断一段时间。
而在这段时间内的请求将不再等待超时,而是直接返回事先设定好的降级结果。这些请求将不占用系统资源,从而避免了服务雪崩的发生。这就是服务熔断。
# 使用
- 开启dashboard
- 开启dashboard后,增加配置,加入dashboard
spring:
cloud:
sentinel:
transport:
# 和sentinel 控制台进行交互
port: 8719
# 控制台
dashboard: localhost:8080
# 饥饿加载
eager: true
# 熔断规则
# 慢调用比例
- 最大 RT(毫秒):以输入200 为例,只要是超过200毫秒就算是慢调用
- 比例阈值:已输入 0.2 为例,就是百分之二十 就算慢调用
- 熔断时长:顾名思义 熔断的时间
- 统计时间(毫秒):以 1000 ms 为例,在1毫秒里面 超过上面的规则的就算慢调用
- 最小请求数: 以200为例,在并发下,每秒超过 200 并发且发生了上面的规则,才会熔断
# API 方式设置熔断规则
在设置 setResource 方法,需要 @SentinelResource 标注 value
- 启动类
package com.gao.sentinel;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import java.util.ArrayList;
import java.util.List;
@SpringBootApplication
public class Sentinel10000Application {
public static void main(String[] args) {
SpringApplication.run(Sentinel10000Application.class, args);
initCircuitBreakingRule();
}
public static void initCircuitBreakingRule() {
List<DegradeRule> rules = new ArrayList<>();
DegradeRule rule = Sentinel10000Application.configDegradeRule();
rules.add(rule);
DegradeRuleManager.loadRules(rules);
}
private static DegradeRule configDegradeRule() {
DegradeRule rule = new DegradeRule();
//指定使用的规则
rule.setResource("list");
//慢调用比例
rule.setGrade(RuleConstant.DEGRADE_GRADE_RT);
//最大 RT
rule.setCount(200);
//比例阈值
rule.setSlowRatioThreshold(0.2);
//指定熔断时长
rule.setTimeWindow(1000);
//最小请求数量
rule.setMinRequestAmount(2);
return rule;
}
}
- 控制器
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.gao.sentinel.entity.Depart;
import com.gao.sentinel.feign.DepartFeignService;
import jakarta.annotation.security.DenyAll;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RequestMapping("/sen")
@RestController
public class ProviderController {
@GetMapping
@SentinelResource(value = "list", blockHandler = "blockErrorMSg")
public String list() {
return "sentinel list ";
}
public String blockErrorMSg(BlockException blockException) {
return "blockErrorMSg" + blockException.getMessage();
}
}