您的位置:首页 > 房产 > 家装 > Spring Cloud基于Sentinel实现限流降级自定义配置返回结果

Spring Cloud基于Sentinel实现限流降级自定义配置返回结果

2024/10/7 20:20:37 来源:https://blog.csdn.net/z1299236067/article/details/142108360  浏览:    关键词:Spring Cloud基于Sentinel实现限流降级自定义配置返回结果

在接口访问流控规则生效,被控制以后会返回一个提示,这个提示我们是可以自定义的

默认返回:

添加自定义类

@Component
public class SentinelConfig implements BlockExceptionHandler {@Overridepublic void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws Exception {//根据限流降级的策略规则,不同的异常返回不同的提示语,String res="";if (e instanceof FlowException) {res ="接口限流了";}else if (e instanceof DegradeException){res ="服务降级了";}else if (e instanceof ParamFlowException){res ="热点参数限流了";}else if (e instanceof SystemBlockException){res ="触发系统保护规则了";}else if(e instanceof AuthorityException){res ="授权规则不通过";}httpServletResponse.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());httpServletResponse.setCharacterEncoding("utf-8");httpServletResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);new ObjectMapper().writeValue(httpServletResponse.getWriter(),res);//跳转到指定页面://request.getRequestDispatcher("/index.jsp").forward(request,response);//跳转到网站//response.sendRedirect("https://www.baidu.com");}
}

添加完成,启动项目。

请求接口并添加流控规则,请求接口测试。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com