Spring Cloud Alibaba-@SentinelResource的使用

1 @SentinelResource的使用

在定义了资源点之后,我们可以通过Dashboard来设置限流和降级策略来对资源点进行保护。同时还能
通过@SentinelResource来指定出现异常时的处理策略。
@SentinelResource 用于定义资源,并提供可选的异常处理和 fallback 配置项。其主要参数如下:

定义限流和降级后的处理方法

  • 方式一:直接将限流和降级方法定义在方法中
@Service
@Slf4j
public class OrderServiceImpl3 {int i = 0;@SentinelResource(value = "message",blockHandler = "blockHandler",//指定发生BlockException时进入的方法fallback = "fallback"//指定发生Throwable时进入的方法)public String message() {i++;if (i % 3 == 0) {throw new RuntimeException();}return "message";}//BlockException时进入的方法public String blockHandler(BlockException ex) {log.error("{}", ex);return "接口被限流或者降级了...";}//Throwable时进入的方法public String fallback(Throwable throwable) {log.error("{}", throwable);return "接口发生异常了...";}
}
  • 方式二: 将限流和降级方法外置到单独的类中
@Service
@Slf4j
public class OrderServiceImpl3 {int i = 0;@SentinelResource(value = "message",blockHandlerClass = OrderServiceImpl3BlockHandlerClass.class,blockHandler = "blockHandler",fallbackClass = OrderServiceImpl3FallbackClass.class,fallback = "fallback")public String message() {i++;if (i % 3 == 0) {throw new RuntimeException();}return "message4";}
}
@Slf4j
public class OrderServiceImpl3BlockHandlerClass {//注意这里必须使用static修饰方法public static String blockHandler(BlockException ex) {log.error("{}", ex);return "接口被限流或者降级了...";}
}
@Slf4j
public class OrderServiceImpl3FallbackClass {
//注意这里必须使用static修饰方法public static String fallback(Throwable throwable) {log.error("{}", throwable);return "接口发生异常了...";}
}

2 Sentinel规则持久化

通过前面的讲解,我们已经知道,可以通过Dashboard来为每个Sentinel客户端设置各种各样的规
则,但是这里有一个问题,就是这些规则默认是存放在内存中,极不稳定,所以需要将其持久化。
本地文件数据源会定时轮询文件的变更,读取规则。这样我们既可以在应用本地直接修改文件来更
新规则,也可以通过 Sentinel 控制台推送规则。以本地文件数据源为例,推送过程如下图所示:

首先 Sentinel 控制台通过 API 将规则推送至客户端并更新到内存中,接着注册的写数据源会将新的规则保存到本地的文件中。
1 编写处理类

package com.itheima.config;
//规则持久化
public class FilePersistence implements InitFunc {@Value("spring.application:name")private String appcationName;@Overridepublic void init() throws Exception {String ruleDir = System.getProperty("user.home") + "/sentinel-
rules/"+appcationName;String flowRulePath = ruleDir + "/flow-rule.json";String degradeRulePath = ruleDir + "/degrade-rule.json";String systemRulePath = ruleDir + "/system-rule.json";String authorityRulePath = ruleDir + "/authority-rule.json";String paramFlowRulePath = ruleDir + "/param-flow-rule.json";this.mkdirIfNotExits(ruleDir);this.createFileIfNotExits(flowRulePath);this.createFileIfNotExits(degradeRulePath);this.createFileIfNotExits(systemRulePath);this.createFileIfNotExits(authorityRulePath);this.createFileIfNotExits(paramFlowRulePath);// 流控规则ReadableDataSource<String, List<FlowRule>> flowRuleRDS = new
FileRefreshableDataSource<>(flowRulePath,flowRuleListParser);FlowRuleManager.register2Property(flowRuleRDS.getProperty());WritableDataSource<List<FlowRule>> flowRuleWDS = new
FileWritableDataSource<>(flowRulePath,this::encodeJson);WritableDataSourceRegistry.registerFlowDataSource(flowRuleWDS);// 降级规则ReadableDataSource<String, List<DegradeRule>> degradeRuleRDS = new
FileRefreshableDataSource<>(degradeRulePath,degradeRuleListParser);DegradeRuleManager.register2Property(degradeRuleRDS.getProperty());WritableDataSource<List<DegradeRule>> degradeRuleWDS = new
FileWritableDataSource<>(degradeRulePath,this::encodeJson);WritableDataSourceRegistry.registerDegradeDataSource(degradeRuleWDS);// 系统规则ReadableDataSource<String, List<SystemRule>> systemRuleRDS = new
FileRefreshableDataSource<>(systemRulePath,systemRuleListParser);SystemRuleManager.register2Property(systemRuleRDS.getProperty());WritableDataSource<List<SystemRule>> systemRuleWDS = new
FileWritableDataSource<>(systemRulePath,this::encodeJson);WritableDataSourceRegistry.registerSystemDataSource(systemRuleWDS);// 授权规则ReadableDataSource<String, List<AuthorityRule>> authorityRuleRDS = new
FileRefreshableDataSource<>(authorityRulePath,authorityRuleListParser);AuthorityRuleManager.register2Property(authorityRuleRDS.getProperty());WritableDataSource<List<AuthorityRule>> authorityRuleWDS = new
FileWritableDataSource<>(authorityRulePath,this::encodeJson);WritableDataSourceRegistry.registerAuthorityDataSource(authorityRuleWDS);// 热点参数规则ReadableDataSource<String, List<ParamFlowRule>> paramFlowRuleRDS = new
FileRefreshableDataSource<>(paramFlowRulePath,paramFlowRuleListParser);ParamFlowRuleManager.register2Property(paramFlowRuleRDS.getProperty());WritableDataSource<List<ParamFlowRule>> paramFlowRuleWDS = new
FileWritableDataSource<>(paramFlowRulePath,this::encodeJson);ModifyParamFlowRulesCommandHandler.setWritableDataSource(paramFlowRuleWDS);}private Converter<String, List<FlowRule>> flowRuleListParser = source ->
JSON.parseObject(source,new TypeReference<List<FlowRule>>() {});private Converter<String, List<DegradeRule>> degradeRuleListParser = source
-> JSON.parseObject(source,new TypeReference<List<DegradeRule>>() {});private Converter<String, List<SystemRule>> systemRuleListParser = source ->
JSON.parseObject(source,new TypeReference<List<SystemRule>>() {});private Converter<String, List<AuthorityRule>> authorityRuleListParser =
source -> JSON.parseObject(source,new TypeReference<List<AuthorityRule>>() {});private Converter<String, List<ParamFlowRule>> paramFlowRuleListParser =
source -> JSON.parseObject(source,new TypeReference<List<ParamFlowRule>>() {});private void mkdirIfNotExits(String filePath) throws IOException {File file = new File(filePath);if (!file.exists()) {file.mkdirs();}}private void createFileIfNotExits(String filePath) throws IOException {File file = new File(filePath);if (!file.exists()) {file.createNewFile();}}private <T> String encodeJson(T t) {return JSON.toJSONString(t);}
}

2 添加配置
在resources下创建配置目录 META-INF/services ,然后添加文件
com.alibaba.csp.sentinel.init.InitFunc
在文件中添加配置类的全路径

com.itheima.config.FilePersistence

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/97154.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

陇剑杯2023WriteUp学习笔记【初赛】

文章目录 数据分析1、hard_webhard_web_1hard_web_2hard_web_3 2、sevrer savesevrer save_1sevrer save_2sevrer save_3sevrer save_4sevrer save_5sevrer save_6sevrer save_7sevrer save_8 3、WiresharkWireshark1_1Wireshark1_2Wireshark1_3Wireshark1_4 4、Incidentrespon…

STM32F4XX/APM32F4XX USB OTA升级

近期在研究USB CDC协议&#xff0c;使用USB Virtual Port Com功能与上位机通讯做了OTA功能。开发平台&#xff1a;MDK529 开发硬件&#xff1a;APM32F411 首先看下手册Flash分布&#xff0c;Flash总共8个扇区。 接下来进行Flash分区。 扇区 0 和 扇区 1做Boo区。 扇区 2做APP跳…

COSCon'23 开源市集:共赴一场草坪上的开源派对

一年一度的开源盛会&#xff0c;第八届中国开源年会&#xff08;COSCon23 &#xff09;&#xff0c;将于10月28~29日&#xff0c;在四川成都市高新区菁蓉汇召开&#xff01;本次大会的主题是&#xff1a;“开源&#xff1a;川流不息、山海相映”&#xff01; 我们预期会有超过1…

记录一下自己对linux分区挂载的理解

一直狠模糊&#xff0c;分两个区&#xff0c;一个挂载/, 一个挂载/home 两者是什么关系 实测 先看挂载的内容 然后umount /home后创建一个新文件 再挂载回去 发现旧分区又回来了&#xff0c;说明路径只是个抽象的概念&#xff0c;分区挂载&#xff0c;互相之间数据是不影响…

Facebook message tag 使用攻略

Messenger 讯息传不出去&#xff1f;无法发送FB 讯息给非好友&#xff1f; 2020年3月&#xff0c;Facebook 为了防止用户被过多的推广或垃圾讯息困扰而更新使用条款&#xff0c;现在商家要用FB传讯息给所有人&#xff08;包括非好友&#xff09;&#xff0c;应该使用 Facebook …

【内推码:NTAMW6c】 MAXIEYE智驾科技2024校招启动啦

MAXIEYE智驾科技2024校招启动啦【内推码&#xff1a;NTAMW6c】 【招聘岗位超多&#xff01;&#xff01;公司食堂好吃&#xff01;&#xff01;】 算法类&#xff1a;感知算法工程师、SLAM算法工程师、规划控制算法工程师、目标及控制算法工程师、后处理算法工程师 软件类&a…

非常详细的 Ceph 介绍、原理、架构

非常详细的 Ceph 介绍、原理、架构 1. Ceph架构简介及使用场景介绍 1.1 Ceph简介 Ceph是一个统一的分布式存储系统&#xff0c;设计初衷是提供较好的性能、可靠性和可扩展性。 Ceph项目最早起源于Sage就读博士期间的工作&#xff08;最早的成果于2004年发表&#xff09;&#…

服务器数据恢复- Ext4文件系统分区挂载报错的数据恢复案例

Ext4文件系统相关概念&#xff1a; 块组&#xff1a;Ext4文件系统的空间被划分为若干个块组&#xff0c;每个块组内的结构大致相同。 块组描述符表&#xff1a;每个块组都对应一个块组描述符&#xff0c;这些块组描述符统一放在文件系统的前部&#xff0c;称为块组描述符表。每…

【机器学习】人工智能概述(文末送书)

&#x1f935;‍♂️ 个人主页&#xff1a;艾派森的个人主页 ✍&#x1f3fb;作者简介&#xff1a;Python学习者 &#x1f40b; 希望大家多多支持&#xff0c;我们一起进步&#xff01;&#x1f604; 如果文章对你有帮助的话&#xff0c; 欢迎评论 &#x1f4ac;点赞&#x1f4…

golang入门笔记——nginx

文章目录 Nginx介绍Nginx的安装Nginx文件Nginx反向代理负载均衡nginx动静分离URLRewrite防盗链nginx高可用配置安全性Nginx限流Nginx缓存集成Lua脚本OpenRestry Nginx介绍 Nginx是一个高性能的HTTP和反向代理服务器&#xff0c;特点是占用内存少&#xff0c;并发能力强&#x…

Doris workload group实战

1.创建测试用户&#xff1a;创建一个用户名为test&#xff0c;密码为test 的用户&#xff1a; create user test% IDENTIFIED BY test;给测试用户赋权&#xff1a;给用户test赋予数据库test.* 权限 grant SELECT_PRIV,LOAD_PRIV,CREATE_PRIV,ALTER_PRIV ON test.* TO test;开…

8K视频来了,8K 视频编辑的最低系统要求

当今 RED、Canon、Ikegami、Sony 等公司的 8K 摄像机以及 8K 电视&#xff0c;许多视频内容制作人和电影制作人正在认真考虑 8K 拍摄、编辑和后期处理&#xff0c;需要什么样的系统来处理如此海量的数据&#xff1f; 中央处理器&#xff08;CPU&#xff09; 首先&#xff0c;…