项目
博客
文档
归档
资源链接
关于我
项目
博客
文档
归档
资源链接
关于我
八.Sentinel自定义异常-整合Open-Feign
2020-11-14
·
softbabet博主
·
原创
·
微服务
·
本文共 280个字,预计阅读需要 1分钟。
### 版本升级-自定义降级异常不向下兼容的坑 默认降级返回数据问题 - 限流和熔断返回的数据有问题 - 微服务交互基本都是json格式,如果让自定义异常信息 - AlibabCloud版本升级,不兼容问题:v2.1.0到v2.2.0后,Sentinel里面依赖进行了改动,`且不向下兼容` **自定义降级返回数据**: 【旧版】实现UrlBlockHandler并且重写blocked方法 ``` @Component public class XUrlBlockHandler implements UrlBlockHandler { @Override public void blocked(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws IOException { //降级业务处理 } } ``` 【新版】实现BlockExceptionHandler并且重写handle方法 ``` public class XUrlBlockHandler implements BlockExceptionHandler { @Override public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws Exception { //降级业务处理 } } ``` ### 自定义降级异常数据开发实战 **异常种类** > `FlowException` //限流异常 > `DegradeException` //降级异常 > `ParamFlowException` //参数限流异常 > `SystemBlockException` //系统负载异常 > `AuthorityException` //授权异常 【新版】实现BlockExceptionHandler并且重写handle方法 ```java @Component public class XUrlBlockHandler implements BlockExceptionHandler { @Override public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws IOException { Map
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)); } } ``` ### Sentinel整合OpenFeign配置实战 整合步骤 - 加入依赖 ```
com.alibaba.cloud
spring-cloud-starter-alibaba-sentinel
``` - 开启Feign对Sentinel的支持 ``` feign: sentinel: enabled: true ``` - 创建容错类, 实现对应的服务接口, 记得加注解 @Service ``` @Service public class VideoServiceFallback implements VideoService { @Override public Video findById(int videoId) { Video video = new Video(); video.setTitle("熔断降级数据"); return video; } @Override public Video saveVideo(Video video) { return null; } } ``` - 配置feign容错类 ``` @FeignClient(value = "yuan-video-service", fallback = VideoServiceFallback.class) ```