SpringCloudAlibaba之Sentinel简单使用

2024-04-23 21:52

本文主要是介绍SpringCloudAlibaba之Sentinel简单使用,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

SpringCloudAlibaba之Sentinel简单使用

文章目录

    • SpringCloudAlibaba之Sentinel简单使用
      • sentinel入门
      • 资源定义
        • SphU(抛出异常方式)
        • SphO(布尔类型方式)
        • @SentinelResource(注解的方式定义)
          • @SentinelResource使用前置条件
          • 使用@SentinelResource定义资源
          • 定义blockHandler和fallback方法(方法名称和@sentinelResoruce的参数名称需要一直,并且方法必须是public修饰)
          • @SentinelResoruce参数释义
          • 完整的service代码(资源定义)
      • 定义sentinel规则
      • 校验规则是否生效

使用sentinel三部曲,

  1. 定义资源
  2. 定义规则
  3. 检验规则是否生效

sentinel入门

  1. 创建基础模块sentinel-boot-service
  • 引入依赖
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>com.alibaba.csp</groupId><artifactId>sentinel-core</artifactId><version>1.8.0</version>
</dependency>
  • 创建主类
@SpringBootApplication
public class SentinelBootServiceApplication {public static void main(String[] args) {SpringApplication.run(SentinelBootServiceApplication.class,args);}
}
  • 创建application.yml
server:port: 8080

资源定义

  1. 定义sentinel资源,sentinel中的资源可以是一段代码,一个方法,甚至是整个应用。sentinel可以保护整个应用

资源必须定义资源名称

  • 创建service/SentinelTestService
SphU(抛出异常方式)
public String sphuTest(){// 1.5.0 版本开始可以直接利用 try-with-resources 特性try(Entry ignored = SphU.entry("sphuTest")) {// 被保护的逻辑return "hello world";} catch (BlockException ex) {// 处理被流控的逻辑return "blocked";}
}

Sphu.entry(resourceName) 可以定义一段sentinel资源,当访问超出sentinel定义的规则后,Sphu.entry方法会抛出BlockException

所以可以在try语句块中定义sentinel的资源,也就是被保护的逻辑。在catch块中捕获BlockException,用来对降级进行处理

SphO(布尔类型方式)
public String sphoTest() {if(SphO.entry("sphoTest")){try {return "hello world";} finally{SphO.exit();}}else{//被限流了,逻辑处理return "被限流了";}
}

SphO.entry(resourceName) 方法可以返回一个boolean值,用于是否通过sentinel管控,必须与SphO.exit()搭配使用

@SentinelResource(注解的方式定义)
@SentinelResource使用前置条件

由于@SentinelResource是通过aop方式进行管控,所以需要引入aspectj模块

<dependency><groupId>com.alibaba.csp</groupId><artifactId>sentinel-annotation-aspectj</artifactId><version>1.8.0</version>
</dependency>
  • SentinelResourceAspect注入到Spring容器中

sentinel-boot-service 的config包下创建SentinelConfig

@Configuration
public class SentinelConfig {//注入@Beanpublic SentinelResourceAspect sentinelResourceAspect(){return new SentinelResourceAspect();}
}
使用@SentinelResource定义资源
private static AtomicInteger atomicInteger = new AtomicInteger(0);@SentinelResource(value = "annotationTest",blockHandler = "blockHandler",fallback = "fallback")public String annotationTest(){int i = atomicInteger.incrementAndGet();if(i % 2 == 0){return "hello world";}else{throw new RuntimeException("something wrong");}}

blockHandler和fallback是两个概念

blockHandler是sentinel对资源进行限流或者熔断时的处理规则

fallback是资源抛出异常后,对异常捕获后的处理

定义blockHandler和fallback方法(方法名称和@sentinelResoruce的参数名称需要一直,并且方法必须是public修饰)
	public String blockHandler(BlockException ex){ex.printStackTrace();return "block handler";}public String fallback(){return "fallback";}

所以上述代码有三段逻辑,第一段正常逻辑返回hello world,第二段,抛出异常,被fallback捕获,返回fallback,第三段,被sentinel限流,被blockHandler处理,返回block handler

@SentinelResoruce参数释义
参数名称类型描述
valueString必需项,用于指定资源的名称。这个名称通常用于在 Sentinel Dashboard 中进行监控和管理。
entryTypeEntryType可选项,指定 entry 的类型。默认为 EntryType.OUT,表示这是一个出站调用。
blockHandlerString可选项,指定处理 BlockException 的函数名称。当原方法被限流或熔断时,会调用这个函数进行异常处理。该函数的访问范围需要是 public,返回类型需要与原方法相匹配,参数类型需要和原方法相匹配并且最后加一个额外的参数,类型为 BlockException。默认情况下,这个函数需要和原方法在同一个类中。
blockHandlerClassClass<?>可选项,当希望使用其他类的函数作为 blockHandler 时,可以指定这个类的 Class 对象。注意,对应的函数必须为 static 函数。
fallbackString可选项,指定回退函数名称,当原方法调用失败时,会调用这个回退函数。回退函数的签名(返回值类型、参数类型)需要与原方法一致。
fallbackClassClass<?>可选项,当希望使用其他类的函数作为回退函数时,可以指定这个类的 Class 对象。同样,对应的函数必须为 static 函数。
resourceTypeint可选项,用于指定资源的类型。这通常用于区分不同类型的资源,以便进行更精细的控制。
exceptionsToIgnoreClass<? extends Throwable>[]可选项,指定需要忽略的异常类型。当原方法抛出这些异常时,Sentinel 不会触发限流或熔断逻辑。

这个注解允许开发者对方法进行细粒度的流量控制,同时提供了异常处理和回退机制,确保系统的可靠性和稳定性。通过合理配置这些参数,可以更加精准地控制应用的流量,避免由于流量过大或异常导致的系统崩溃。

完整的service代码(资源定义)
@Service
public class SentinelTestService {private static AtomicInteger atomicInteger = new AtomicInteger(0);public String sphuTest(){// 1.5.0 版本开始可以直接利用 try-with-resources 特性try(Entry ignored = SphU.entry("sphuTest")) {// 被保护的逻辑return "hello world";} catch (BlockException ex) {// 处理被流控的逻辑return "blocked";}}public String sphoTest() {if(SphO.entry("sphoTest")){try {return "hello world";} finally{SphO.exit();}}else{//被限流了,逻辑处理return "被限流了";}}@SentinelResource(value = "annotationTest",blockHandler = "blockHandler",fallback = "fallback")public String annotationTest(){int i = atomicInteger.incrementAndGet();if(i % 2 == 0){return "hello world";}else{throw new RuntimeException("something wrong");}}public String blockHandler(BlockException ex){ex.printStackTrace();return "block handler";}public String fallback(){return "fallback";}
}

定义sentinel规则

sentinel的规则有很多种,此文章示例,仅用流控来测试sentinel定义的资源信息

在config/SentinelRuleConfig下分别创建上面三个资源的流控规则,如下

@Configuration
public class SentinelRuleConfig {@PostConstructpublic void init(){List<FlowRule> rules = new ArrayList<>();FlowRule rule = new FlowRule();//定义规则适用的资源名称rule.setResource("sphuTest");rule.setGrade(RuleConstant.FLOW_GRADE_QPS);//定义每秒被保护的代码块最多运行2次rule.setCount(2);rules.add(rule);FlowRule sphoTestRule = new FlowRule();//定义规则适用的资源名称sphoTestRule.setResource("sphoTest");sphoTestRule.setGrade(RuleConstant.FLOW_GRADE_QPS);//定义每秒被保护的代码块最多运行2次sphoTestRule.setCount(2);rules.add(sphoTestRule);FlowRule annotationTestRule = new FlowRule();//定义规则适用的资源名称annotationTestRule.setResource("annotationTest");annotationTestRule.setGrade(RuleConstant.FLOW_GRADE_QPS);//定义每秒被保护的代码块最多运行2次annotationTestRule.setCount(2);rules.add(annotationTestRule);FlowRuleManager.loadRules(rules);}
}
  • setResource:设置资源名称
  • setGrade:设置流控的类型,此处通过QPS,即每秒的访问量
  • setCount: 设置每秒访问量的阈值,当大于2时,触发sentinel流控

校验规则是否生效

  • 新建入口SentinelTestController,并分别创建三个uri对应三个资源的访问
public class SentinelTestController {@Resourceprivate SentinelTestService sentinelTestService;@GetMapping("/sphuTest")public String sphuTest(){return sentinelTestService.sphuTest();}@GetMapping("/sphoTest")public String sphoTest(){return sentinelTestService.sphoTest();}@GetMapping("/annotationTest")public String annotationTest(){return sentinelTestService.annotationTest();}
}
  • 启动sentinel-boot-service项目模块,并通过浏览器访问
  1. sphuTest
  • 访问sphuTest,可以看到正常返回hello world
http://localhost:8080/sentinel/sphuTest
-> hello world
  • 快速刷新sphuTest,可以看到blockedhello world出现
http://localhost:8080/sentinel/sphuTest
-> hello world
-> blocked    
  1. sphotest
  • 访问sphOTest,可以看到正常返回hello world
http://localhost:8080/sentinel/sphoTest
-> hello world
  • 快速刷新sphoTest,可以看到被限流了hello world出现
http://localhost:8080/sentinel/sphoTest
-> hello world
-> 被限流了
  1. annotationTest
  • 低频率刷新annotationTest,可以看到hello world和fallback交替出现,这里由于业务逻辑是执行一次,抛一次异常,异常捕获被fallback执行,所以交替出现
http://localhost:8080/sentinel/annotationTest
-> hello world
-> fallback
-> hello world
-> fallback
-> hello world
-> fallback
  • 高频率刷新,可以看到hello worldfallbackblock handler都会出现。

在高频率刷新中,可能会执行正常逻辑(未限流,未异常情况),可能执行到fallback逻辑(异常情况),block handler(达到设定的流控QPS阈值)

这篇关于SpringCloudAlibaba之Sentinel简单使用的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/929987

相关文章

SpringBoot基础框架详解

《SpringBoot基础框架详解》SpringBoot开发目的是为了简化Spring应用的创建、运行、调试和部署等,使用SpringBoot可以不用或者只需要很少的Spring配置就可以让企业项目快... 目录SpringBoot基础 – 框架介绍1.SpringBoot介绍1.1 概述1.2 核心功能2

Spring Boot 事务详解(事务传播行为、事务属性)

《SpringBoot事务详解(事务传播行为、事务属性)》SpringBoot提供了强大的事务管理功能,通过@Transactional注解可以方便地配置事务的传播行为和属性,本文将详细介绍Spr... 目录Spring Boot 事务详解引言声明式事务管理示例编程式事务管理示例事务传播行为1. REQUI

使用Nginx配置文件服务器方式

《使用Nginx配置文件服务器方式》:本文主要介绍使用Nginx配置文件服务器方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1. 为什么选择 Nginx 作为文件服务器?2. 环境准备3. 配置 Nginx 文件服务器4. 将文件放入服务器目录5. 启动 N

使用nohup和--remove-source-files在后台运行rsync并记录日志方式

《使用nohup和--remove-source-files在后台运行rsync并记录日志方式》:本文主要介绍使用nohup和--remove-source-files在后台运行rsync并记录日... 目录一、什么是 --remove-source-files?二、示例命令三、命令详解1. nohup2.

Spring AI 实现 STDIO和SSE MCP Server的过程详解

《SpringAI实现STDIO和SSEMCPServer的过程详解》STDIO方式是基于进程间通信,MCPClient和MCPServer运行在同一主机,主要用于本地集成、命令行工具等场景... 目录Spring AI 实现 STDIO和SSE MCP Server1.新建Spring Boot项目2.a

Qt之QMessageBox的具体使用

《Qt之QMessageBox的具体使用》本文介绍Qt中QMessageBox类的使用,用于弹出提示、警告、错误等模态对话框,具有一定的参考价值,感兴趣的可以了解一下... 目录1.引言2.简单介绍3.常见函数4.按钮类型(QMessage::StandardButton)5.分步骤实现弹窗6.总结1.引言

Python使用Reflex构建现代Web应用的完全指南

《Python使用Reflex构建现代Web应用的完全指南》这篇文章为大家深入介绍了Reflex框架的设计理念,技术特性,项目结构,核心API,实际开发流程以及与其他框架的对比和部署建议,感兴趣的小伙... 目录什么是 ReFlex?为什么选择 Reflex?安装与环境配置构建你的第一个应用核心概念解析组件

Qt中Qfile类的使用

《Qt中Qfile类的使用》很多应用程序都具备操作文件的能力,包括对文件进行写入和读取,创建和删除文件,本文主要介绍了Qt中Qfile类的使用,具有一定的参考价值,感兴趣的可以了解一下... 目录1.引言2.QFile文件操作3.演示示例3.1实验一3.2实验二【演示 QFile 读写二进制文件的过程】4.

spring security 超详细使用教程及如何接入springboot、前后端分离

《springsecurity超详细使用教程及如何接入springboot、前后端分离》SpringSecurity是一个强大且可扩展的框架,用于保护Java应用程序,尤其是基于Spring的应用... 目录1、准备工作1.1 引入依赖1.2 用户认证的配置1.3 基本的配置1.4 常用配置2、加密1. 密

WinForms中主要控件的详细使用教程

《WinForms中主要控件的详细使用教程》WinForms(WindowsForms)是Microsoft提供的用于构建Windows桌面应用程序的框架,它提供了丰富的控件集合,可以满足各种UI设计... 目录一、基础控件1. Button (按钮)2. Label (标签)3. TextBox (文本框