在前面我们对Sentinel做了一个详细的介绍,可以手动的通过Sentinel提供的SphU类来保护资源。这种做法不好的地方在于每个需要限制的地方都得写代码,从 0.1.1 版本开始,Sentinel 提供了 @SentinelResource 注解的方式,非常方便。

要使用注解来保护资源需要引入下面的Maven依赖:

<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-annotation-aspectj</artifactId>
<version>1.4.1</version>
</dependency>

引入之后我们需要配置SentinelResourceAspect切面让其生效,因为是通过SentinelResourceAspect切面来实现的,我这边以Spring Boot中使用进行配置示列:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.alibaba.csp.sentinel.annotation.aspectj.SentinelResourceAspect; @Configuration
public class AopConfiguration { @Bean
public SentinelResourceAspect sentinelResourceAspect() {
return new SentinelResourceAspect();
} }

然后在需要限制的方法上加SentinelResource注解即可:

@SentinelResource(value = "get", blockHandler = "exceptionHandler")
@Override
public String get(String id) {
return "http://cxytiandi.com";
} public String exceptionHandler(String id, BlockException e) {
e.printStackTrace();
return "错误发生在" + id;
}

SentinelResource:value

表示资源名,必填项

SentinelResource:blockHandler

处理 BlockException 的方法名,可选项。若未配置,则将 BlockException 直接抛出。

  • blockHandler 函数访问范围需要是 public
  • 返回类型需要与原方法相匹配
  • 参数类型需要和原方法相匹配并且最后加一个额外的参数,类型为 BlockException
  • blockHandler 函数默认需要和原方法在同一个类中

如果你不想让异常处理方法跟业务方法在同一个类中,可以使用 blockHandlerClass 为对应的类的 Class 对象,注意对应的函数必需为 static 函数,否则无法解析。

业务方法:

@SentinelResource(value = "get2", blockHandler = "handleException", blockHandlerClass = { ExceptionUtil.class })
@Override
public String get2() {
return "http://cxytiandi.com";
}

异常处理类:

import com.alibaba.csp.sentinel.slots.block.BlockException;

public final class ExceptionUtil {

    public static String handleException(BlockException ex) {
System.err.println("错误发生: " + ex.getClass().getCanonicalName());
return "error";
} }

如何测试?

我们可以在Spring Boot的启动类中定义规则,然后快速访问接口,就可以看出效果啦,或者用压力测试工具ab等。

@SpringBootApplication
public class App {
public static void main(String[] args) {
initFlowRules();
SpringApplication.run(App.class, args);
} private static void initFlowRules() {
List<FlowRule> rules = new ArrayList<>(); FlowRule rule = new FlowRule();
rule.setResource("get");
rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
rule.setCount(1);
rules.add(rule); rule = new FlowRule();
rule.setResource("get2");
rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
rule.setCount(1);
rules.add(rule); FlowRuleManager.loadRules(rules);
}
}

源码分析

只需要配置了SentinelResourceAspect就可以使用注解,我们来简单的看下SentinelResourceAspect的源码

@Aspect
public class SentinelResourceAspect extends AbstractSentinelAspectSupport { @Pointcut("@annotation(com.alibaba.csp.sentinel.annotation.SentinelResource)")
public void sentinelResourceAnnotationPointcut() {
} @Around("sentinelResourceAnnotationPointcut()")
public Object invokeResourceWithSentinel(ProceedingJoinPoint pjp) throws Throwable {
// 获取当前访问的方法
Method originMethod = resolveMethod(pjp);
// 获取方法上的SentinelResource注解
SentinelResource annotation = originMethod.getAnnotation(SentinelResource.class);
if (annotation == null) {
// Should not go through here.
throw new IllegalStateException("Wrong state for SentinelResource annotation");
}
// 获取资源名
String resourceName = getResourceName(annotation.value(), originMethod);
EntryType entryType = annotation.entryType();
Entry entry = null;
try {
entry = SphU.entry(resourceName, entryType, 1, pjp.getArgs());
Object result = pjp.proceed();
return result;
} catch (BlockException ex) {
// 处理被限制的异常,回调事先配置的异常处理方法
return handleBlockException(pjp, annotation, ex);
} catch (Throwable ex) {
Tracer.trace(ex);
throw ex;
} finally {
if (entry != null) {
entry.exit();
}
}
}
}

上面是整个切面的代码,对所有加了SentinelResource注解的方法进去切入。细节代码在AbstractSentinelAspectSupport中,大家自己去看看。

欢迎加入我的知识星球,一起交流技术,免费学习猿天地的课程(http://cxytiandi.com/course)

PS:目前星球中正在星主的带领下组队学习Sentinel,等你哦!

Sentinel: 使用注解限流的更多相关文章

  1. Sentinel限流示例:编码和注解限流

    一.Sentinel 是什么? 随着微服务的流行,服务和服务之间的稳定性变得越来越重要.Sentinel 以流量为切入点,从流量控制.熔断降级.系统负载保护等多个维度保护服务的稳定性. Sentine ...

  2. Spring Cloud Alibaba基础教程:使用Sentinel实现接口限流

    最近管点闲事浪费了不少时间,感谢网友libinwalan的留言提醒.及时纠正路线,继续跟大家一起学习Spring Cloud Alibaba. Nacos作为注册中心和配置中心的基础教程,到这里先告一 ...

  3. Spring Cloud Alibaba 使用Sentinel实现接口限流

    Sentinel是什么 Sentinel的官方标题是:分布式系统的流量防卫兵.从名字上来看,很容易就能猜到它是用来作服务稳定性保障的.对于服务稳定性保障组件,如果熟悉Spring Cloud的用户,第 ...

  4. 快速体验 Sentinel 集群限流功能,只需简单几步

    ️ Pic by Alibaba Tech on Facebook 集群限流 可以限制某个资源调用在集群内的总 QPS,并且可以解决单机流量不均导致总的流控效果不佳的问题,是保障服务稳定性的利器. S ...

  5. Sentinel整合Dubbo限流实战(分布式限流)

    之前我们了解了 Sentinel 集成 SpringBoot实现限流,也探讨了Sentinel的限流基本原理,那么接下去我们来学习一下Sentinel整合Dubbo及 Nacos 实现动态数据源的限流 ...

  6. springBoot整合Sentinel实现降级限流熔断

    由于hystrix的停止更新,以及阿里Sentinel在历年双十一的贡献.项目中使用了Sentinel,今天我们来讲讲Sentinel的入门教程,本文使用1.6.3版本进行讲解 本文通过Sentine ...

  7. 微服务架构 | 5.2 基于 Sentinel 的服务限流及熔断

    目录 前言 1. Sentinel 基础知识 1.1 Sentinel 的特性 1.2 Sentinel 的组成 1.3 Sentinel 控制台上的 9 个功能 1.4 Sentinel 工作原理 ...

  8. Spring Cloud alibaba网关 sentinel zuul 四 限流熔断

    spring cloud alibaba 集成了 他内部开源的 Sentinel 熔断限流框架 Sentinel 介绍 官方网址 随着微服务的流行,服务和服务之间的稳定性变得越来越重要.Sentine ...

  9. Spring Cloud Alibaba系列(五)sentinel实现服务限流降级

    一.sentinel是什么 sentinel的官方名称叫分布式系统的流量防卫兵.Sentinel 以流量为切入点,从流量控制.熔断降级.系统负载保护等多个维度保护服务的稳定性.在Spring Clou ...

随机推荐

  1. Rust从入门到放弃(1)—— hello,world

    安装及环境配置 特点:安全,性能,并发 rust源配置 RLS安装 cargo rust管理工具,该工具可以愉快方便的管理rust工程 #!/bin/bash mkdir learn cd learn ...

  2. 2019-9-2-win10-uwp-判断本地ip

    原文:2019-9-2-win10-uwp-判断本地ip title author date CreateTime categories win10 uwp 判断本地ip lindexi 2019-0 ...

  3. 整理:VS常用快捷键

    F1-F12 F1 帮助 F3: 查找下一个 Shift+F3: 查找上一个 F5: 启动调试 Ctrl+F5: 开始执行(不调试) Shift+F5: 停止调试 Ctrl+Shift+F5: 重启调 ...

  4. mysql只显示表名和备注

    查看某个数据下的表及其备注: select table_name,table_comment from information_schema.tables where table_schema='db ...

  5. javascript:警告(alert 消息对话框),确认(confirm 消息对话框)

    原文:https://blog.csdn.net/u012110719/article/details/41926315

  6. Java生鲜电商平台-技术方案与文档下载

    Java生鲜电商平台-技术方案与文档下载 说明:任何一个好的项目,都应该有好的文档与设计方案,包括需求文档,概要设计,详细设计,测试用例,验收报告等等,类似下面这个图: 有以下几个管理域: 1. 开发 ...

  7. i春秋-第三届“百越杯”福建省高校网络空间安全大赛-Do you know upload?

    进去提示有提示文件包含漏洞 拿到源码发现这里上传验证只有MIME验证 可直接抓包改 image/gif 绕过 接下来就是这次学到的点了 菜刀连接过后怎么都找不到flag文件,但是这里找到了数据库配置文 ...

  8. 【转】合并两个List并去掉重复项

    原文:https://my.oschina.net/jack90john/blog/1493170 工作中很多时候需要用到合并两个List并去除其中的重复内容.这是一个很简单的操作,这里主要是记录一下 ...

  9. Linux磁盘分区/格式化/挂载目录

    分区及挂载目录 以CentOS7.2为例,一般我们服务端应用部署前需要确认部署机的磁盘空间及挂载目录.操作如下: 如上图,如果操作系统是新装的,未挂盘的话需要先挂载盘.操作如下: fdisk -l # ...

  10. 2-1Numpy概述

    In [1]: import numpy as np In [2]: array=[1,2,3,4,5] array+1#没定义成numpy.ndarray类型是不能直接操作的   --------- ...