Spring Cloud 整合Sentinel

1、引入依赖

版本说明 · alibaba/spring-cloud-alibaba Wiki · GitHub

父pom

XML 复制代码
<spring.cloud.version>Hoxton.SR12</spring.cloud.version>
<spring.cloud.alibaba.version>2.2.10-RC1</spring.cloud.alibaba.version>

Sentinel应用直接引用starter

XML 复制代码
<dependency>    
    <groupId>com.alibaba.cloud</groupId>    
    <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>

2、配置规则

限流着重于防止整体系统的入口流量过大,通过量化控制进入系统的请求速度。

降级是在系统负载过高或部分服务不可用时,采取的一种策略,它允许系统牺牲部分非核心功能或降低服务质量,以保证核心功能的正常运行。

java 复制代码
    // 限流配置规则
    @PostConstruct
    public static void initFlowRules() {
        List<FlowRule> rules = new ArrayList<>();
        FlowRule rule = new FlowRule();
        rule.setResource("ordering"); //设置资源名称
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);//QPS 每秒的访问量
        // Set limit QPS to 20.
        rule.setCount(2);
        rules.add(rule);
        FlowRuleManager.loadRules(rules);
    }
    // 降级规则
    //@PostConstruct
    public  void initFlowRules2() {
        List<DegradeRule> rules = new ArrayList<>();
         DegradeRule rule = new DegradeRule();
        rule.setResource("ordering2"); //设置资源名称
        rule.setGrade(DEGRADE_GRADE_EXCEPTION_RATIO);
        // Set limit QPS to 20.
        rule.setCount(0.5);
        rule.setMinRequestAmount(10);
        rule.setTimeWindow(10); // 10s 熔断时长10s
        rule.setStatIntervalMs(10*1000); 10s 统计时长,统计的窗口(单位为 ms)
        rules.add(rule);
        DegradeRuleManager.loadRules(rules);
    }

3、为接口设置熔断与降级方法

3.1 blockHandler与fallback命名规则

  1. blockHandler方法应该接收与原始方法相同类型的参数,并且额外添加一个 BlockException 类型的参数,用于传递被 Sentinel 阻塞的具体原因。

命名规则是:

1:原方法名 + "_blockHandler",比如在示例中,对应的 blockHandler 方法应该是 ordering_blockHandler(Integer id, BlockException ex)

2:必须为static方法

  1. fallback方法应该接收与原始方法相同类型的参数

命名规则是:

1:原方法名 + "_fallback",此方法应该接收与原始方法相同的参数列表,并返回与原始方法相同的返回类型。

2:必须为static方法

在示例中,对应的 fallback 方法应该是 ordering_fallback(Integer id)也可以ordering_fallback(Integer id, Throwable ex)``

上述的 _blockHandler_fallback 后面是可以带上任意的参数类型,但至少需要包含原始方法的所有参数类型,以及在 blockHandler 方法中加入 BlockException 参数。

3.2 触发条件

  1. blockHandler

    1. 触发条件:当资源访问由于触发了 Sentinel 的流控(QPS 超过阈值等情况)规则而被阻止时,会触发 blockHandler 指定的方法。该方法主要用于处理因流量控制而导致的阻塞情况。

    2. 示例中 blockHandler="ordering_blockHandler" 表示如果 ordering 方法因为 Sentinel 流控规则而被阻止时,将调用 OrderController 类中的 ordering_blockHandler 方法进行处理。

  2. fallback

    1. 触发条件:通常在服务不稳定或者异常抛出时触发。对于 Sentinel 来说,若开启了熔断(如因多次调用超时或异常),则会触发熔断进入半开状态,后续请求会直接进入 fallback 处理逻辑,或者在某些资源执行过程中发生了异常也会触发 fallback。

    2. 示例中 fallback="ordering_fallback" 表示如果 ordering 方法出现异常或者满足 Sentinel 熔断策略时,将调用 OrderController 类中的 ordering_fallback 方法进行回退处理。

    3. 在熔断期间,不再调用原始方法,而是直接调用降级方法

3.3验证限流

java 复制代码
@RestController
@RequestMapping("/api/order")
@Slf4j
public class OrderController {

    private  static AtomicInteger count = new AtomicInteger(0);
    
    @GetMapping
    @SentinelResource(
            value = "HelloWorld",
            blockHandlerClass=OrderController.class,
            blockHandler = "ordering_blockHandler")
    public String ordering(Integer id) {
        int i = count.incrementAndGet();
        log.debug(id + "进来了 - > "+i);
        return "下单成功";
    }

    public static String  ordering_blockHandler(Integer id,BlockException ex){
        int i = count.incrementAndGet();
        log.debug("熔断了 -> "+i );
        return "系统繁忙,请稍后重试";
    }
    @PostConstruct //初始化执行
    private  void initFlowRules(){
        List<FlowRule> rules = new ArrayList<>();
        FlowRule rule = new FlowRule();
        rule.setResource("HelloWorld");
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        // Set limit QPS to 20.
        rule.setCount(2);
        rules.add(rule);
        FlowRuleManager.loadRules(rules);
    }
}

3.4 验证降级

java 复制代码
@RestController
@RequestMapping("/api/order2")
@Slf4j
public class Order2Controller {
    
    @GetMapping
    @SentinelResource(
            value = "ordering2",
            fallbackClass= Order2Controller.class,
            fallback = "ordering_fallback")
    public String ordering(Integer id) {
        log.debug("进来了");
        if (id == 4) {
            throw new IllegalArgumentException("参数异常");
        }
        return "下单成功";
    }
    //? 什么时候触发? ordering_fallback 有什么要求吗?
    public static String ordering_fallback(Integer id, Throwable ex) {
        log.debug("降级");
        return "降级了";
    }

    @PostConstruct //初始化执行 降级规则
    private  void initDegradeRule(){

        List<DegradeRule> rules = new ArrayList<>();
        DegradeRule rule = new DegradeRule("ordering2")
                .setGrade(CircuitBreakerStrategy.ERROR_COUNT.getType())
                // Max allowed response time 错误数量
                .setCount(2)
                // Retry timeout (in second) 熔断10s
                .setTimeWindow(20)
                .setMinRequestAmount(10) //最小请求数
                .setStatIntervalMs(10*1000);//10s 统计时长,统计的窗口(单位为 ms)
        rules.add(rule);

        DegradeRuleManager.loadRules(rules);

    }
}

4、验证接口

5、高级配置

5.1流量控制规则 (FlowRule)

5.2 熔断降级规则 (DegradeRule)

5.3 系统保护规则 (SystemRule)

Sentinel 系统自适应限流从整体维度对应用入口流量进行控制,结合应用的 Load、CPU 使用率、总体平均 RT、入口 QPS 和并发线程数等几个维度的监控指标,通过自适应的流控策略,让系统的入口流量和系统的负载达到一个平衡,让系统尽可能跑在最大吞吐量的同时保证系统整体的稳定性。

java 复制代码
private void initSystemProtectionRule() {
  List<SystemRule> rules = new ArrayList<>();
  SystemRule rule = new SystemRule();
  rule.setHighestSystemLoad(10);
  rules.add(rule);
  SystemRuleManager.loadRules(rules);
}

5.4 访问控制规则 (AuthorityRule)

很多时候,我们需要根据调用方来限制资源是否通过,这时候可以使用 Sentinel 的访问控制(黑白名单)的功能。黑白名单根据资源的请求来源(origin)限制资源是否通过,若配置白名单则只有请求来源位于白名单内时才可通过;若配置黑名单则请求来源位于黑名单时不通过,其余的请求通过。授权规则,即黑白名单规则(AuthorityRule)非常简单,主要有以下配置项:

  • resource:资源名,即限流规则的作用对象

  • limitApp:对应的黑名单/白名单,不同 origin 用 ,分隔,如 appA,appB

  • strategy:限制模式,AUTHORITY_WHITE 为白名单模式,AUTHORITY_BLACK 为黑名单模式,默认为白名单模式

5.5热点规则 (ParamFlowRule)

parameter-flow-control | Sentinel

相关推荐
这儿有一堆花8 分钟前
用原生脚本编写无害恶作剧
windows
因我你好久不见13 分钟前
Windows部署springboot jar支持开机自启动
windows·spring boot·jar
夜流冰34 分钟前
Excel - MS Support for Excel: 2 Collaborate
数据库·windows·excel
林瞅瞅1 小时前
PowerShell 启动卡顿?内存飙升?原来是 800MB 的历史记录在作祟!
windows
Shepherd06192 小时前
【Windows Server 实战】WAC 反向代理配置
windows
云小逸2 小时前
【windows系统编程】第一章 Windows 系统核心架构与基础概念
windows·架构
怣疯knight3 小时前
Docker Desktop 4.55.0版本安装成功教程
windows·docker
liulilittle5 小时前
VEthernet 框架实现 tun2socks 的技术原理
网络·windows·c#·信息与通信·通信
独钓寒江雨5 小时前
win11在安全模式下删除360tray.exe
windows·电脑
PieroPc6 小时前
Windows 远程到 PVE 9.X Mac os (像window远程桌面)
windows·mac·远程桌面