在实际应用过程中,我们可能需要限流的层面不仅限于接口。可能对于某个方法的调用限流,对于某个外部资源的调用限流等都希望做到控制。对此,我们需要学习使用@SentinelResource注解,灵活的定义控制资源以及如何配置控制策略
按资源名称限流加后续处理
Module:cloudalibaba-sentinel-service8401
pom新增依赖
<dependency><!-- 引入自己定义的api通用包,可以使用Payment支付Entity -->
<groupId>com.atguigu.springcloud</groupId>
<artifactId>cloud-api-common</artifactId>
<version>${project.version}</version>
</dependency>
这个依赖来自自己的模板,这里的这个依赖就是去数据库查询的一部分业务处理
新增Controller
@RestController
public class RateLimitController
{
@GetMapping("/byResource")
@SentinelResource(value = "byResource",blockHandler = "handleException")
public CommonResult byResource()
{
return new CommonResult(200,"按资源名称限流测试OK",new Payment(2020L,"serial001"));
}
public CommonResult handleException(BlockException exception)
{
return new CommonResult(444,exception.getClass().getCanonicalName()+"\t 服务不可用");
}
}
图形配置和代码关系
表示1秒钟内查询次数大于1,就跑到我们自定义的处流,限流
测试1
1秒钟点击1下,OK
超过上述,疯狂点击,返回了自己定义的限流处理信息,限流发生
额外问题
此时关闭问服务8401看看
Sentinel控制台,流控规则消失了?????
临时/持久?
按照Url地址限流加后续处理
通过访问的URL来限流,会返回Sentinel自带默认的限流处理信息
Controller修改为:
@RestController
public class RateLimitController
{
@GetMapping("/byResource")
@SentinelResource(value = "byResource",blockHandler = "handleException")
public CommonResult byResource()
{
return new CommonResult(200,"按资源名称限流测试OK",new Payment(2020L,"serial001"));
}
public CommonResult handleException(BlockException exception)
{
return new CommonResult(444,exception.getClass().getCanonicalName()+"\t 服务不可用");
}
@GetMapping("/rateLimit/byUrl")
@SentinelResource(value = "byUrl")
public CommonResult byUrl()
{
return new CommonResult(200,"按url限流测试OK",new Payment(2020L,"serial002"));
}
}
测试2
访问一次
http://localhost:8401/rateLimit/byUrl
正常
疯狂点击http://localhost:8401/rateLimit/byUrl
会返回Sentinel自带的限流处理结果
上面兜底方案面临的问题
1 系统默认的,没有体现我们自己的业务要求。
2 依照现有条件,我们自定义的处理方法又和业务代码耦合在一块,不直观。
3 每个业务方法都添加一个兜底的,那代码膨胀加剧。
4 全局统一的处理方法没有体现。
客户自定义限流处理逻辑
创建CustomerBlockHandler类用于自定义限流处理逻辑
测试后我们自定义的出来了
控制类增加新的业务
@GetMapping("/rateLimit/customerBlockHandler")
@SentinelResource(value = "customerBlockHandler",
blockHandlerClass = CustomerBlockHandler.class, blockHandler = "handleException2")
public CommonResult customerBlockHandler()
{
return new CommonResult(200,"按客户自定义限流处理逻辑");
}
自定义通用的限流处理逻辑
blockHandlerClass = CustomerBlockHandler.class
blockHandler = handleException2
上述配置:找CustomerBlockHandler类里的handleException2方法进行兜底处理 定义通用的限流处理逻辑
测试3
测试后我们自定义的出来了
到此这篇关于Java @SentinelResource全面介绍的文章就介绍到这了,更多相关Java @SentinelResource内容请搜索编程学习网以前的文章希望大家以后多多支持编程学习网!
本文标题为:Java @SentinelResource全面介绍


- SpringBoot使用thymeleaf实现一个前端表格方法详解 2023-06-06
- ExecutorService Callable Future多线程返回结果原理解析 2023-06-01
- 基于Java Agent的premain方式实现方法耗时监控问题 2023-06-17
- JSP页面间传值问题实例简析 2023-08-03
- Springboot整合minio实现文件服务的教程详解 2022-12-03
- Java中的日期时间处理及格式化处理 2023-04-18
- JSP 制作验证码的实例详解 2023-07-30
- 深入了解Spring的事务传播机制 2023-06-02
- Spring Security权限想要细化到按钮实现示例 2023-03-07
- Java实现顺序表的操作详解 2023-05-19