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文件中添加依赖包:

        
            com.alibaba.csp
            sentinel-annotation-aspectj
            1.6.1
        

        
            com.alibaba.csp
            sentinel-core
            1.6.1
        

        
            com.alibaba.csp
            sentinel-datasource-apollo
            1.6.1
        

增加一个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

你可能感兴趣的:(SentinelResource注解限流)