场景
SpringCloudAlibaba集成Sentinel之热点参数限流的使用:
https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/125258705
在上面进行限流之后回调方法的设置时是通过如下方式
@GetMapping("/testHotKey") @SentinelResource(value = "testHotKey",blockHandler = "deal_testHotKey") public String testHotKey(@RequestParam(value = "p1",required = false) String p1, @RequestParam(value = "p2",required = false) String p2) { return "------testHotKey"; } public String deal_testHotKey (String p1, String p2, BlockException exception) { return "------deal_testHotKey,o(╥﹏╥)o"; //sentinel系统默认的提示:Blocked by Sentinel (flow limiting) }
如果要限制的接口较多总不能每一个接口都要写一个限流的处理回调方法吧,有没有可以全局
设置通用的回调处理方法。实现业务和配置的低耦合。
注:
博客:
https://blog.csdn.net/badao_liumang_qizhi
关注公众号
霸道的程序猿
获取编程相关电子书、教程推送与免费下载。
实现
1、在下面的基础上实现与Sentinel的集成。
SpringCloudAlibaba中使用Sentinel实现流量控制以及流控规则详解:
https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/125216632
2、新建一个handler类用来处理限流的回调
package com.badao.springcloudalibabademo.myhandler; import com.alibaba.csp.sentinel.slots.block.BlockException; import com.badao.springclouddemo.entities.CommonResult; public class CustomerBlockHandler { public static CommonResult handlerException(BlockException exception) { return new CommonResult(4444,"按客戶自定义,global handlerException----1"); } public static CommonResult handlerException2(BlockException exception) { return new CommonResult(4444,"按客戶自定义,global handlerException----2"); } }
注意这里的CommonResult是自定义的返回结果的封装类
package com.badao.springclouddemo.entities; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor public class CommonResult<T> { private Integer code; private String message; private T data; public CommonResult(Integer code, String message) { this(code,message,null); } }
然后这个handler其方法必须是static,然后这里声明了两个方法,可以在下面设置限流回调时指定使用哪个方法进行处理。
2、然后在需要进行限流兜底处理的接口上添加注解
@SentinelResource(value = "customerBlockHandler", blockHandlerClass = CustomerBlockHandler.class, blockHandler = "handlerException2")
并指明是哪个类的哪个方法来处理。
完整接口
package com.badao.springcloudalibabademo.controller; import com.alibaba.csp.sentinel.annotation.SentinelResource; import com.badao.springcloudalibabademo.myhandler.CustomerBlockHandler; import com.badao.springclouddemo.entities.CommonResult; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class RateLimitController { @GetMapping("/rateLimit/customerBlockHandler") @SentinelResource(value = "customerBlockHandler", blockHandlerClass = CustomerBlockHandler.class, blockHandler = "handlerException2") public CommonResult customerBlockHandler() { return new CommonResult(200,"按客戶自定义"); } }
3、效果演示
博客园:
https://www.cnblogs.com/badaoliumangqizhi/
关注公众号
霸道的程序猿
获取编程相关电子书、教程推送与免费下载。