Sentinel规则

news2024/10/5 21:16:22

一、服务熔断测试

例子:

application.properties配置文件

server.port=8083

spring.application.name=order

#spring.cloud.nacos.discovery.server-addr=http://192.168.44.64:80

spring.cloud.nacos.discovery.server-addr=localhost:8848

spring.cloud.sentinel.transport.port=9999

spring.cloud.sentinel.transport.dashboard=localhost:8888

spring.cloud.sentinel.web-context-unify=false

自定义业务类CustomerBlockHandler

public class CustomerBlockHandler {
    public static ResponseMsg handlerException(BlockException exception) {
        return new ResponseMsg(404, "自定义1111111111111");
    }

}

 controller类

@RestController
@RequestMapping
public class Test2Controller {
    @GetMapping("/t1")
    @SentinelResource(value = "CustomerBlockHandler",
            blockHandlerClass = CustomerBlockHandler.class,
            blockHandler = "handlerException")
    public ResponseMsg t1(){
        return ResponseMsg.SUCCESS(200,"成功",null);
    }
}

Sentinel配置

二、配置流控效果

1. 快速失败(默认)

直接失败,抛出异常,不做任何额外的处理,是最简单的效果

2. Warm Up

它从开始阈值到最大QPS阈值会有一个缓冲阶段,一开始的阈值是最大QPS阈值的1/3,然后慢慢.增长,直到最大阈值,适用于将突然增大的流量转换为缓步增长的场景

例子:

Controller类

 @GetMapping("/t2")
    public ResponseMsg t2(){
        return ResponseMsg.SUCCESS(200,"成功",null);
    }

 Sentinel配置

设置阈值为 10,预热时间是 5 秒,逐渐增加到阈值上限,所以会有一个初始阈值

初始阈值 = 阈值上限 / coldFactor, coldFactor 是冷加载因子,默认为3

上面这个配置的效果就是:在 5 秒内最大阈值是 3(10/codeFactor),超过5秒,最大阈值为10

3.  排队等待

让请求以均匀的速度通过,单机阈值为每秒通过数量,其余的排队等待; 它还会让设置一个超时时间,当请求超过超时间时间还未处理,则会被丢弃

排队等待方式会严格控制请求通过的间隔时间,也即是让请求以均匀的速度通过,对应的是漏桶算法。

注意:匀速排队,让请求以匀速通过,阈值类型必须设置为QPS,否则无效,匀速排队模式暂时不支持 QPS > 1000 的场景

例子:

Controller

  @GetMapping("/t3")
    public ResponseMsg t3(){
        return ResponseMsg.SUCCESS(200,"成功",null);
    }
  Sentinel配置

当阈值设为 2 的时候,则代表一秒匀速的通过 2 个请求,也就是每个请求平均间隔恒定为 1000 / 2 = 500 ms,每一个请求的最长等待时间(maxQueueingTimeMs)为 0.5s 。

三、降级规则

降级规则就是设置当满足什么条件的时候,对服务进行降级

慢调用比例

例子:

Controller

 

 @GetMapping("/t4")
    public ResponseMsg t4(){
        try {
            Thread.sleep(600);//线程睡眠600毫秒
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        return ResponseMsg.SUCCESS(200,"成功",null);
    }
 Sentinel配置

 

 测试

这样在5秒内查询的结果一直为空

异常比例

当资源的每秒请求量>=5,并且每秒异常总数占通过量的比值超过阈值之后,资源进入降级状态,即在接下的时间窗口智能,对这个方法的调用都会自动地返回。异常比率的阈值范围是[0.0,1.0],代表0%~100%

例子:

Controller

@GetMapping("/t5")
    public ResponseMsg t5(){
        System.out.println(1/0);
        return ResponseMsg.SUCCESS(200,"成功",null);
    }
Sentinel配置

测试

异常数

跟异常比例基本上一样

例子:

Controller

 

 @GetMapping("/t5")
    public ResponseMsg t5(){
        System.out.println(1/0);
        return ResponseMsg.SUCCESS(200,"成功",null);
    }
Sentinel配置

测试

四、热点规则

热点参数流控规则是一种更细粒度的流控规则, 它允许将规则具体到参数上。

热点规则普通使用

Controller

 @GetMapping("/t6")
    @SentinelResource(value = "test6")
    //注意这里必须使用这个注解标识,热点规则不生效
    public ResponseMsg t6(String str , Integer number){
        return ResponseMsg.SUCCESS(number,"成功",str);
    }

Sentinel配置

测试 

热点规则增强使用

controller

跟上面的普通使用一样

@GetMapping("/t6")
    @SentinelResource(value = "test6")
    //注意这里必须使用这个注解标识,热点规则不生效
    public ResponseMsg t6(String str , Integer number){
        return ResponseMsg.SUCCESS(number,"成功",str);
    }

Sentinel配置

测试

五、授权规则

很多时候,我们需要根据调用来源来判断该次请求是否允许放行,这时候可以使用 Sentinel 的来源 访问控制的功能。来源访问控制根据资源的请求来源(origin)限制资源是否通过: 若配置白名单,则只有请求来源位于白名单内时才可通过; 若配置黑名单,则请求来源位于黑名单时不通过,其余的请求通过

例子:

自定义来源处理规则

@Component
public class RequestOriginParserDefinition implements RequestOriginParser {
    @Override
    public String parseOrigin(HttpServletRequest request) {
        String serviceName = request.getParameter("serviceName");
        return serviceName;
    }
}

 

Controller

@GetMapping("/t7")
    public ResponseMsg t7(String str , Integer number){
        return ResponseMsg.SUCCESS(number,"成功",str);
    }

Sentinel配置

测试

 

 

黑名单同样如此  只不过携带的参数是设置的参数将被拦截

六、全局异常的返回

异常配置类

@ControllerAdvice//全局异常
public class Test2Exception {
    @ResponseBody
    @ExceptionHandler({Exception.class})
    public ResponseMsg test(){
        return new ResponseMsg(500,"错误!!!!!");
    }
}

controller

 

 @GetMapping("/t5")
    public ResponseMsg t5(){
        System.out.println(1/0);
        return ResponseMsg.SUCCESS(200,"成功",null);
    }

测试

 

七、Sentinel规则持久化

以通过Dashboard来为每个Sentinel客户端设置各种各样的规则,但是这里有一个问题,就是这些规则默认是存放在内存中,极不稳定,所以需要将其持久化。

方法一

添加到nacos里面

在配置文件application中添加以下内容

spring.cloud.sentinel.datasource.ds1.nacos.data-id=${spring.application.name}

spring.cloud.sentinel.datasource.ds1.nacos.data-type=json

spring.cloud.sentinel.datasource.ds1.nacos.server-addr=localhost:8848

spring.cloud.sentinel.datasource.ds1.nacos.group-id=DEFAULT_GROUP

spring.cloud.sentinel.datasource.ds1.nacos.rule-type=flow

 在nacos中为cloudalibaba-sentinel-service(可以在配置文件自定义)服务添加对应配置。

[

        {

                "resource": "/rateLimit/customerBlockHandler",#/rateLimit/customerBlockHandler

                "limitApp": "default",

                "grade": 1,

                "count": 1,

                "strategy": 0,

                "controlBehavior": 0,

                "clusterMode": false

        }

]

resource: 资源名称;

imitApp: 来源应用;

grade: 阈值类型,0表示线程数,1表示QPS;

count: 单机阈值;

strategy: 流控模式,0表示直接,1表示关联,2表示链路;

controlBehavior: 流控效果,0表示快速失败,1表示。Warm Up,2表示排队等待。

clusterMode: 是否集群。

 

方法二

使用文件

先创建一个FilePersistence类

import com.alibaba.csp.sentinel.command.handler.ModifyParamFlowRulesCommandHandler;
import com.alibaba.csp.sentinel.datasource.*;
import com.alibaba.csp.sentinel.init.InitFunc;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityRule;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityRuleManager;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRuleManager;
import com.alibaba.csp.sentinel.slots.system.SystemRule;
import com.alibaba.csp.sentinel.slots.system.SystemRuleManager;
import com.alibaba.csp.sentinel.transport.util.WritableDataSourceRegistry;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import org.springframework.beans.factory.annotation.Value;
import java.io.File;
import java.io.IOException;
import java.util.List;
public class FilePersistence implements InitFunc {
    @Value("${spring.application.name}")
    private String appcationName;
    @Override
    public 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);
    }
}
在对应的微服务下面的resources里面创一个目录

写上刚才的配置类位置

这样每次设置的配置项目重启都不会清空了

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

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

基于单片机的智能家居安保系统(论文+源码)

1.系统设计 本次基于单片机的智能家居安保系统设计&#xff0c;在功能上如下&#xff1a; 1&#xff09;以51单片机为系统控制核心&#xff1b; 2&#xff09;温度传感器、人体红外静释电、烟雾传感器来实现检测目的&#xff1b; 3&#xff09;以GSM模块辅以按键来实现远/近程…

Nginx(四) absolute_redirect、server_name_in_redirect、port_in_redirect 请求重定向指令组合测试

本篇文章主要用来测试absolute_redirect、server_name_in_redirect和port_in_redirect三个指令对Nginx请求重定向的影响&#xff0c;Nginx配置详解请参考另一篇文章 Nginx(三) 配置文件详解 接下来&#xff0c;在Chrome无痕模式下进行测试。 测试1&#xff1a;absolute_redi…

yolov5模型代码怎么修改

yaml配置文件 深度乘积因子 宽度乘积因子 所有版本只有这两个参数的不同&#xff0c;s m l x逐渐加宽加深 各种类型层参数对照 backbone里的各层&#xff0c;在这里解析&#xff0c;只需要改.yaml里的各层参数就能控制网络结构 修改网络结构 第一步&#xff1a;把新加的模块…

用人话讲解深度学习中CUDA,cudatookit,cudnn和pytorch的关系

参考链接 本人学习使用&#xff0c;侵权删谢谢。用人话讲解深度学习中CUDA&#xff0c;cudatookit&#xff0c;cudnn和pytorch的关系 CUDA CUDA是显卡厂商NVIDIA推出的运算平台。 CUDA™是一种由NVIDIA推出的通用并行计算架构&#xff0c;是一种并行计算平台和编程模型&…

在屏幕上打印杨辉三角

我们先来看看杨辉三角长什么样的&#xff1a; 我们一起来看一看它的规则: 1. 每一行的第一个数字和最后一个数字都是1 2. 从第三行开始&#xff0c;中间的数字和最后一个数字等于它上方两个数字之和 我们可以很好的发现下面的数字就是由该数字上面一行和上一列加上该数字的…

redis设置密码

首先到redis的下载目录下&#xff1a;运行 redis-cli 查看redis密码&#xff1a; config get requirepass 设置redis密码为123456&#xff1a; config set requirepass 123456

SQL中的数据类型和规范化,助力数据存储优化

大家好&#xff0c;目前优化数据存储对于获得良好的性能始终至关重要&#xff0c;选择合适的数据类型并应用正确的规范化过程对于决定其性能至关重要。本文将介绍最重要和最常用的数据类型和规范化过程。 一、SQL中的数据类型 SQL中主要有两种数据类型&#xff1a;字符串和数…

【前沿学习】美国零信任架构发展现状与趋势研究

转自&#xff1a;美国零信任架构发展现状与趋势研究 摘要 为了应对日趋严峻的网络安全威胁&#xff0c;美国不断加大对零信任架构的研究和应用。自 2022 年以来&#xff0c;美国发布了多个零信任战略和体系架构文件&#xff0c;开展了多项零信任应用项目。在介绍美国零信任战略…

Numpy数组进阶_Python数据分析与可视化

Numpy数组进阶 Numpy的广播机制高级索引整数数组索引布尔索引花式索引 数组迭代 Numpy的广播机制 广播 (Broadcast) 是 numpy 对不同形状 (shape) 的数组&#xff0c;进行数值计算的方式。 对数组的算术运算通常在相应的元素上进行&#xff0c;当运算中的 2 个数组的形状不同时…

DNS1(Bind软件)

名词解释 1、DNS&#xff08;Domain Name System&#xff09; DNS即域名系统&#xff0c;它是一个分层的分布式数据库&#xff0c;存储着IP地址与主机名的映射 2、域和域名 域为一个标签&#xff0c;而有多个标签域构成的称为域名。例如hostname.example.com&#xff0c;其…

java接收前端easyui datagrid传递的数组参数

这篇文章分享一下怎么在easyui的datagrid刷新表格时&#xff0c;在后端java代码中接收datagrid传递的数组参数。 数组来源于技能的tagbox&#xff08;标签框&#xff09;&#xff0c;tagbox和combobox的区别是tagbox可以选择多项。 标签框渲染的代码为 $("#skill_ids"…

分类预测 | Matlab实现PSO-BiLSTM-Attention粒子群算法优化双向长短期记忆神经网络融合注意力机制多特征分类预测

分类预测 | Matlab实现PSO-BiLSTM-Attention粒子群算法优化双向长短期记忆神经网络融合注意力机制多特征分类预测 目录 分类预测 | Matlab实现PSO-BiLSTM-Attention粒子群算法优化双向长短期记忆神经网络融合注意力机制多特征分类预测分类效果基本描述程序设计参考资料 分类效果…

ubuntu 23.04从源码编译安装rocm运行tensorflow-rocm

因为ubuntu22.04的RDP不支持声音转发&#xff0c;所以下载了ubuntu23.04.但官方的rocm二进制包最高只支持ubuntu22.04&#xff0c;不支持ubuntu 23.04&#xff0c;只能自己从源码编译虽然有网友告诉我可以用docker运行rocm。但是我已经研究了好几天&#xff0c;沉没成本太多&am…

12v24v60v高校同步降压转换芯片推荐

12V/24V/60V 高校同步降压转换芯片推荐&#xff1a; 对于需要高效、稳定、低噪音的降压转换芯片&#xff0c;推荐使用WD5030E和WD5105。这两款芯片都是采用同步整流技术&#xff0c;具有高效率、低噪音、低功耗等优点&#xff0c;适用于各种电子设备。 WD5030E是一款高效率…

一文浅入Springboot+mybatis-plus+actuator+Prometheus+Grafana+Swagger2.9.2开发运维一体化

Swagger是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTFUL风格的Web服务,是非常流行的API表达工具。 Swagger能够自动生成完善的 RESTFUL AP文档,,同时并根据后台代码的修改同步更新,同时提供完整的测试页面来调试API。 Prometheus 是一个开源的服务监控系统和时…

Microsoft发布了一份关于其产品安全修复的 11 月报告。

&#x1f47e; 平均每天有 50 多个漏洞被发现&#xff0c;其中一些会立即被网络犯罪分子利用。我们把那些现在很受网络犯罪分子欢迎&#xff0c;或者根据我们的预测&#xff0c;在不久的将来可能会被大量利用的漏洞称为趋势漏洞。 在攻击者开始利用这些漏洞之前 12 小时&#…

adb手机调试常用命令

查看手机型号 adb shell getprop ro.product.model 查看电池状况 adb shell dumpsys battery 查看分辨率 adb shell wm size 查看屏幕密度 adb shell wm density 查看显示屏参数 adb shell dumpsys window displays 查看android_id adb shell settings get secure android…

flutter web 中嵌入一个html

介绍 flutter web 支持使用 HtmlElementView嵌入html import dart:html; import dart:ui as ui; import package:flutter/cupertino.dart;class WebWidget extends StatelessWidget {const WebWidget({super.key});overrideWidget build(BuildContext context) {DivElement fr…

【二分法】

二分法可以在有序排列中&#xff0c;通过不断对半切割数据&#xff0c;提高数据查找效率。 lst [1,4,6,7,45,66,345,767,788,999] n 66 left 0 right len(lst)-1 while left < right: #边界&#xff0c;当右边比左边还小的时候退出循环 mid (left right)//2 …

vue2项目修改编译巨慢

前言&#xff1a;我们的一个vue项目在给新同事后他说编译贼慢&#xff0c;一个小修改项5分钟才能自动编译成功&#xff0c;我把项目放到新电脑上也巨慢&#xff0c;升级了nodejs好使了一些&#xff0c;但还是慢&#xff0c;最后引入webpack后巨快&#xff0c; 在项目的package…