SentinelResource注解限流

@SentinelResource(value = "helloAnother", blockHandler =  = "defaultFallback")

使用注解限流,只需要将上述注解加在被限流的方法上,如:

@SentinelResource(value = "hello", blockHandler = "helloFallback")
public String hello(long s) {
   if (s < 0) {
      throw new IllegalArgumentException("invalid arg");
   }
   return String.format("Hello at %d", s);
}

value参数为必须配置的参数,值为配置的资源名,并不是方法名。

blockHandler非必填参数,指定被限流时调用的方法。若不自定义方法,则会抛出限流异常。

参数配置可以写在Apollo或者用代码文件的方式进行配置。

自定义被限流后的执行方法需注意:

被限流方法的参数必须作为自定义执行方法的参数,另外多加一个参数,BlockException e。

public String helloFallback(long s, BlockException ex) {
        ex.printStackTrace();
        return "Oops, error occurred at " + s;
}

附加:

@SentinelResource(value = "ResourceName" , blockHandler = "limitFlow", blockHandlerClass = ExceptionUtils.class)

若使用此种注解引入限流执行方法,需注意ExceptionUtils.class中对应的方法必须为静态方法。

在pom文件中添加依赖包:

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

        <dependency>
            <groupId>com.alibaba.csp</groupId>
            <artifactId>sentinel-core</artifactId>
            <version>1.6.1</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba.csp</groupId>
            <artifactId>sentinel-datasource-apollo</artifactId>
            <version>1.6.1</version>
        </dependency>

增加一个config文件:

@Configuration
public class AopConfiguration {

    //此处应有读取配置信息的操作    

    @Bean
    public SentinelResourceAspect sentinelResourceAspect() {
        return new SentinelResourceAspect();
    }
}

此限流,只针对在AOP切面上的方法。若按照此方法限流不生效,极有可能因为被限流的方法不在AOP。

更多参考链接:

https://github.com/alibaba/Sentinel/tree/1.6.2/sentinel-demo

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值