当前位置: 首页 > news >正文

Spring Cloud 整合Sentinel

1、引入依赖

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

父pom

<spring.cloud.version>Hoxton.SR12</spring.cloud.version>
<spring.cloud.alibaba.version>2.2.10-RC1</spring.cloud.alibaba.version>

Sentinel应用直接引用starter

<dependency>    <groupId>com.alibaba.cloud</groupId>    <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>

2、配置规则

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

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

    // 限流配置规则@PostConstructpublic 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);}// 降级规则//@PostConstructpublic  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 熔断时长10srule.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验证限流


@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 验证降级


@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 和并发线程数等几个维度的监控指标,通过自适应的流控策略,让系统的入口流量和系统的负载达到一个平衡,让系统尽可能跑在最大吞吐量的同时保证系统整体的稳定性。

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

http://www.lryc.cn/news/346245.html

相关文章:

  • Java入门基础学习笔记4——开发Helloworld入门程序
  • 了解WebSocket
  • 从开发角度理解漏洞成因(02)
  • Web实时通信的学习之旅:轮询、WebSocket、SSE的区别以及优缺点
  • TMS320F280049 CLB模块--LUT4 OUTLUT(4)
  • 功能测试_分类_用例_方法
  • [沫忘录]MySQL 锁
  • 噪声嵌入提升语言模型微调性能
  • XML文档基本语法
  • git开发工作流程
  • JDK生成https配置
  • 通过 Java 操作 redis -- set 集合基本命令
  • WebSocket前后端建立以及使用
  • C++数据结构之链表树图的存储
  • 又一位互联网大佬转行当网红,能写进简历么?
  • Codeforces Round 134 (Div. 1) A. Ice Skating (并查集)
  • 深入了解 Flask Request
  • 前端测试策略与实践:单元测试、E2E测试与可访问性审计
  • 修改el-checkbox样式
  • UE5缺少SDK,而无法在windows平台打包的解决方法
  • 4G,5G执法记录仪人脸识别、人脸比对使用说明
  • 掌握SEO优化的关键:提升网站排名的秘籍(如何提高网站seo排名)
  • 大模型微调之 在亚马逊AWS上实战LlaMA案例(九)
  • Php php7的特性
  • node pnpm修改默认包的存储路径
  • Adobe-Premiere-CEP 扩展 入门-视频剪辑-去气口插件-Silence Remover
  • 基于多目标灰狼算法的冷热电联供型微网低碳经济调度
  • Python 正则表达式 (?=...) 和 (?<=...) 符号
  • Vue.js中使用JavaScript实现路由跳转详解
  • 社群裂变:从微光到星火的社群增长奥秘