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

服务流控(Sentinel)

引入依赖

<!-- 必须的 -->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId>
</dependency><!-- sentinel 核心库 -->
<dependency><groupId>com.alibaba.csp</groupId><artifactId>sentinel-core</artifactId><version>1.8.0</version>
</dependency>

实现流控

编码实现

  • 限流实现
    private static final Logger logger = LoggerFactory.getLogger(HelloController.class);private static final String RESOURCE_NAME = "hello";@RequestMapping("/hello")public String hello() {Entry entry = null;// 务必保证finally会被执行try {// 资源名可使用任意有业务语义的字符串entry = SphU.entry(RESOURCE_NAME);// 被保护的业务逻辑// do something...String str = "hello world";logger.info("++++++++++++" + str);return str;} catch (BlockException e1) {// 资源访问阻止,被限流或被降级// 进行相应的处理操作logger.info("block!!!!!");return "被流控了!!!!";} catch (Exception e) {// 若需要配置降级规则。则需要通过这种方式记录业务异常Tracer.traceEntry(e, entry);} finally {if (entry != null) {entry.exit();}}return null;}
  • 注册流控规则
    @PostConstructprivate static void initFlowControlRules() { // 通常设置在服务提供方// 流控规则列表List<FlowRule> flowRuleList = new ArrayList<>();// 流控规则FlowRule helloFlowRule = new FlowRule();// 设置流控的资源名称helloFlowRule.setResource(RESOURCE_NAME);// 设置流控规则 QPShelloFlowRule.setGrade(RuleConstant.FLOW_GRADE_QPS);// 设置流控的阈值// Set limit QPS to 20helloFlowRule.setCount(1);flowRuleList.add(helloFlowRule);FlowRuleManager.loadRules(flowRuleList);}
  • 效果呈现

注解实现

  • 引入依赖
<!--  @SentinelResource  -->
<dependency><groupId>com.alibaba.csp</groupId><artifactId>sentinel-annotation-aspectj</artifactId><version>1.8.0</version>
</dependency>
  • 增加切面
    • 启动类
    @Beanpublic SentinelResourceAspect sentinelResourceAspect() {return new SentinelResourceAspect();}
    • 配置类
/*** 1. 使用注解@SentinelResource* 2. 使用了 Spring AOP* 3. 通过配置的方式将 SentinelResourceAspect 注册为一个 Spring Bean*/
@Configuration
public class AopConfiguration {@Beanpublic SentinelResourceAspect sentinelResourceAspect() {return new SentinelResourceAspect();}
}
  • 注解使用
    /*** 使用注解 使用Sentinel** @SentinelResource: 依赖:* <dependency>*      <groupId>com.alibaba.csp</groupId>*      <artifactId>sentinel-annotation-aspectj</artifactId>*      <version>1.8.0</version>* </dependency>* 1. value: 资源名称* 2. blockHandler 流控降低处理器 (默认和接口实现方法在同一个类中)* 3. blockHandlerClass 指定处理器类* 4. fallback  业务异常处理* 5. fallbackClass 指定异常处理器类* 6. blockHandler 和 fallback 同时配置, blockHandler 优先级高* 7. exceptionsToIgnore 排除不需要处理的异常 -> exceptionsToIgnore = {}*/@RequestMapping("/user")@SentinelResource(value = USER_RESOURCE_NAME, blockHandler = "blockHandlerForGetUser",
//            fallback = "fallBackForGetUser",exceptionsToIgnore = {})public User getUser(String id) {// int i = 1 / 0;return new User(id, "Quentin");}/*** 注意:* 1. 必须是public, 若放在其他类中 blockHandlerClass 则必须为 public static* 2. 返回值 需和原接口方法的返回值保持一致 且 参数包含原方法的参数* 3. 额外增加  异常参数 BlockException** @param id* @param be* @return*/public User blockHandlerForGetUser(String id, BlockException be) {logger.info("++++++++注解流控");return new User(id, "被流控了!!!");}
  • 增加流控规则
    @PostConstructprivate static void initFlowControlRules() { // 通常设置在服务提供方// 流控规则列表List<FlowRule> flowRuleList = new ArrayList<>();// 流控规则FlowRule userFlowRule = new FlowRule();// 设置流控的资源名称userFlowRule.setResource(USER_RESOURCE_NAME);// 设置流控规则 QPSuserFlowRule.setGrade(RuleConstant.FLOW_GRADE_QPS);// 设置流控的阈值// Set limit QPS to 20userFlowRule.setCount(1);flowRuleList.add(userFlowRule);FlowRuleManager.loadRules(flowRuleList);}
  • 效果

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

相关文章:

  • 点亮代码之灯,程序员的夜与电脑
  • ClickHouse--07--Integration 系列表引擎
  • 前端架构: 脚手架框架之yargs的11种基础核心特性的应用教程
  • MySQL性能调优篇(6)-主从复制的配置与管理
  • Linux第49步_移植ST公司的linux内核第1步_获取linux源码
  • 怎样学习Windows下命令行编写
  • 数据结构第十六天(二叉树层序遍历/广度优先搜索(BFS)/队列使用)
  • 6.s081 学习实验记录(八)Networking
  • 图解贝塞尔曲线生成原理
  • 租房招聘|在线租房和招聘平台|基于Springboot的在线租房和招聘平台设计与实现(源码+数据库+文档)
  • 简单试验:用Excel进行爬虫
  • SQL 精讲-MySql 常用函数,MySQL语句精讲和举例
  • nlp中如何数据增强
  • python:xml.etree,用 xmltodict 转换为json数据,生成jstree所需的文件
  • C#log4net日志保存到Sqlserver数据库表(16)
  • SpringCloud-Nacos集群搭建
  • 第十五届蓝桥杯全国软件和信息技术专业人才大赛个人赛(软件赛)软件测试组竞赛规则及说明
  • 【算法与数据结构】496、503、LeetCode下一个更大元素I II
  • 当AGI遇到人形机器人
  • Pytorch卷积层原理和示例 nn.Conv1d卷积 nn.Conv2d卷积
  • Qt 实现无边框窗口1.0
  • Flume(二)【Flume 进阶使用】
  • 静态时序分析:SDC约束命令set_clock_transition详解
  • web 发展阶段 -- 详解
  • 车载软件架构 —— Adaptive AUTOSAR软件架构中操作系统
  • 前缀和算法-截断数组
  • Kubernetes实战:Kubernetes中网络插件calico Daemon Sets显示异常红色
  • 深入探究:JSONCPP库的使用与原理解析
  • 字节UC伯克利新研究 | Magic-Me:简单有效的主题ID可控视频生成框架
  • 2024免费人像摄影后期处理工具Portraiture4.1