问题

通过@SentinelResource设置定制的fallback、blockhandler方法。

  1. @GetMapping(value = "/test")
  2. @SentinelResource(value = "test", fallbackClass = ControllerFallback.class, fallback = "handlerFallback", // fallback只负责业务异常
  3. blockHandlerClass = ControllerBlockHandler.class, blockHandler = "handlerException1", // blockHandler只负责sentinel控制台配置违规
  4. exceptionsToIgnore = {IllegalArgumentException.class})
  5. public Result<String> test(@RequestParam(value = "id") String id) throws InterruptedException {
  6. log.info("有用户访问 test");
  7. int i = 10 / 0;
  8. // TimeUnit.SECONDS.sleep(http://img.itvip666.com/group1/M00/00/09/wKgB_F-eNtOAVp9cAABTsoCoCHE995.png);
  9. return new Result<>().ok("测试通过啦");
  10. }

但是我们也不可能每个限制的方法上面,都要去设置@SentinelResource;这样代码太冗余了。

全局统一处理

定义一个类实现 BlockExceptionHandler 接口

注意

  • Alibaba v2.1.0和Alibaba v2.2.0不一样,接口发生了变化
  • 下面的代码是针对 spring cloud Alibaba v2.2.0
  1. /**
  2. * 定义BlockExceptionHandler接口限流处理逻辑
  3. */
  4. public class CustomBlockHandler implements BlockExceptionHandler {
  5. @Override
  6. public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws Exception {
  7. Result<String> result = new Result<String>();
  8. // 不通的异常可以做不同的事情
  9. // 如果是限流异常
  10. if (e instanceof FlowException) {
  11. result = new Result<String>().error("限流了");
  12. } else if (e instanceof DegradeException) {
  13. result = new Result<String>().error("降级异常");
  14. } else if (e instanceof ParamFlowException) {
  15. result = new Result<String>().error("热点参数限流");
  16. } else if (e instanceof SystemBlockException) {
  17. result = new Result<String>().error("系统异常");
  18. } else if (e instanceof AuthorityException) {
  19. result = new Result<String>().error("授权异常");
  20. }
  21. httpServletResponse.setStatus(500);
  22. httpServletResponse.setCharacterEncoding("utf-8");
  23. httpServletResponse.setHeader("Content-Type","application/json;charset=UTF-8");
  24. httpServletResponse.setContentType("application/json;charset=utf-8");
  25. new ObjectMapper()
  26. .writeValue(httpServletResponse.getWriter(),result);
  27. }
  28. }
  • CustomBlockHandlerConfig,将自定义的降级处理类加入到spring容器中
  1. @Configuration
  2. public class CustomBlockHandlerConfig {
  3. @Bean
  4. public BlockExceptionHandler getBlockExceptionHandler() {
  5. return new CustomBlockHandler();
  6. }
  7. }

测试

我设置的是流控,当快速点击的时候就会发生限流异常

1610803450962.png