SpringCloudAlibaba:@SentinelResource

x33g5p2x  于2021-10-29 转载在 Spring  
字(1.8k)|赞(0)|评价(0)|浏览(490)

一、按资源名称添加流控规则

1.新建controller

  1. @RestController
  2. public class SentinelResourceController {
  3. @GetMapping("/resource")
  4. @SentinelResource(value = "resource",blockHandler = "handleException")
  5. public String resource(){
  6. return "SentinelResourceController invoke resource success";
  7. }
  8. public String handleException(BlockException e){
  9. return "SentinelResourceController invoke handleException";
  10. }
  11. }

然后启动项目,在浏览器输入地址,然后在sentinel的控制台就可以看到了

2.新建流控规则

3.测试

刷新频繁会出现

二、自定义异常返回类

1.自定义handler

  1. public class ZrsBlockHandler {
  2. public static String handler1Exception(BlockException exception){
  3. return "ZrsBlockHandler invoke handler【1】Exception";
  4. }
  5. public static String handler2Exception(BlockException exception){
  6. return "ZrsBlockHandler invoke handler【2】Exception";
  7. }
  8. }

2.修改SentinelResourceController

  1. @RestController
  2. public class SentinelResourceController {
  3. @GetMapping("/resource")
  4. @SentinelResource(value = "resource",blockHandler = "handleException")
  5. public String resource(){
  6. return "SentinelResourceController invoke resource success";
  7. }
  8. public String handleException(BlockException e){
  9. return "SentinelResourceController invoke handleException";
  10. }
  11. @GetMapping("/handler1")
  12. @SentinelResource(value = "handler1Exception",blockHandlerClass = ZrsBlockHandler.class,
  13. blockHandler = "handler1Exception")
  14. public String handler1(){
  15. return "SentinelResourceController invoke resource success";
  16. }
  17. @GetMapping("/handler2")
  18. @SentinelResource(value = "handler2Exception",blockHandlerClass = ZrsBlockHandler.class,
  19. blockHandler = "handler2Exception")
  20. public String handler2(){
  21. return "SentinelResourceController invoke resource success";
  22. }
  23. }

3.启动服务

  1. http://localhost:8005/handler1
  2. http://localhost:8005/handler2

4.添加流控规则

5.测试

频繁访问

相关文章