Skip to content

限流和熔断返回的数据有问题,微服务交互基本都是json格式,一般都需要自定义异常信息,v2.1.0到v2.2.0后,Sentinel里面依赖进行了改动,且不向下兼容,因此本篇文章还将讲解新旧版本的差异。

【旧版】自定义降级返回数据

java
@Component
public class XdclassUrlBlockHandler implements UrlBlockHandler {
  @Override
  public void blocked(HttpServletRequest request, HttpServletResponse response, BlockException e) throws IOException {
     //降级业务处理
  }
}

【新版】自定义降级返回数据

java
public class XdclassUrlBlockHandler implements BlockExceptionHandler {
 
  @Override
  public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {
  //降级业务处理
  }
}

自定义降级异常

  • 限流异常:FlowException
  • 降级异常:DegradeException
  • 参数限流异常:ParamFlowException
  • 系统负载异常:SystemBlockException
  • 授权异常:AuthorityException

【新版】实现BlockExceptionHandler并且重写handle方法

java
@Component
public class XdclassUrlBlockHandler implements BlockExceptionHandler {
  @Override
  public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws IOException {
      Map<String,Object> backMap=new HashMap<>();
      if (e instanceof FlowException){
          backMap.put("code",-1);
          backMap.put("msg","限流-异常啦");
      }else if (e instanceof DegradeException){
          backMap.put("code",-2);
          backMap.put("msg","降级-异常啦");
      }else if (e instanceof ParamFlowException){
          backMap.put("code",-3);
          backMap.put("msg","热点-异常啦");
      }else if (e instanceof SystemBlockException){
          backMap.put("code",-4);
          backMap.put("msg","系统规则-异常啦");
      }else if (e instanceof AuthorityException){
          backMap.put("code",-5);
          backMap.put("msg","认证-异常啦");
      }

      // 设置返回json数据
      httpServletResponse.setStatus(200);
      httpServletResponse.setHeader("content-Type","application/json;charset=UTF-8");
      httpServletResponse.getWriter().write(JSON.toJSONString(backMap));
  }
}