天天看点

SpringCloudAlibaba——Sentinel(@SentinelResource实例)

SpringCloudAlibaba——Sentinel(@SentinelResource实例)

修改cloudalibaba-sentinel-service8401模块

添加依赖(添加commons依赖,自定义的entity model)

<dependency>
        <groupId>org.cjd</groupId>
        <artifactId>cloud-api-commons</artifactId>
</dependency>
           

在controller中添加业务

@RestController
    @Slf4j
    public class RateLimitController {
        
        @GetMapping("/byResource")
        @SentinelResource(value = "byResourceQWER", blockHandler = "handlerException")
        public CommonResult byResource(){
            
            return new CommonResult(200, "按资源名称限流测试OK", new Payment(2020L, "serial001"));
        }
        public CommonResult handlerException(BlockException e){
            return new CommonResult(404, e.getClass().getCanonicalName()+"\t 服务不可用");
        }
    }
           

新增限流规则:按资源名进行限流, @SentinelResource(value = “byResourceQWER”, blockHandler = “handlerException”)名称为value的值

SpringCloudAlibaba——Sentinel(@SentinelResource实例)

测试

SpringCloudAlibaba——Sentinel(@SentinelResource实例)

默认的url限流:即getmapping路径

SpringCloudAlibaba——Sentinel(@SentinelResource实例)

新增流控规则

SpringCloudAlibaba——Sentinel(@SentinelResource实例)

测试

SpringCloudAlibaba——Sentinel(@SentinelResource实例)

总结

  • 通过注解(资源名)指定名字,可以指定方法进行后续处理,即转到自定义方法处理
  • 直接流控路径无自定义兜底方法,会直接调用默认的界面

自定义兜底方法与业务类解耦

如果我们要为接口添加自定义的兜底方法,这个处理方法又要和业务代码耦合在一起,一多就很臃肿

可以通过创建自定义限流类来解耦

创建自定义限流类

SpringCloudAlibaba——Sentinel(@SentinelResource实例)

在业务类中补充完整注解

SpringCloudAlibaba——Sentinel(@SentinelResource实例)

测试(添加限流规则之后)

SpringCloudAlibaba——Sentinel(@SentinelResource实例)

继续阅读