sentinel上下文配置(玩转Sentinel定义异常-整合Open-Feign)

AlibabaCloud版本升级-⾃定义降级异常不向下兼容的坑

默认降级返回数据问题

  • 限流和熔断返回的数据有问题
  • 微服务交互基本都是json格式,如果让⾃定义异常信息

AlibabCloud版本升级,不兼容问题

  • v2.1.0到v2.2.0后,Sentinel⾥⾯依赖进⾏了改动,且不向下兼容

⾃定义降级返回数据

  • 【旧版】实现UrlBlockHandler并且重写blocked⽅法

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

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

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

新版sentinel⾃定义降级异常数据开发实战

异常种类

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

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

@Component public class AlibabaUrlBlockHandler implements BlockExceptionHandler { @Override public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception { Map<String,Object> result = new HashMap<>(); if (e instanceof FlowException){ result.put("code",-1); result.put("message","限流异常!"); } else if (e instanceof DegradeException){ result.put("code",-2); result.put("message","降级异常!"); } else if (e instanceof ParamFlowException){ result.put("code",-3); result.put("message","热点异常!"); } else if (e instanceof SystemBlockException){ result.put("code",-4); result.put("message","系统规则异常!"); } else if (e instanceof AuthorityException){ result.put("code",-5); result.put("message","认证异常!"); } //设置返回数据 response.setStatus(200); response.setHeader("content-type","application/json;charset=UTF-8"); response.getWriter().write(JSON.toJSONString(result)); } }

降级测试

sentinel上下文配置(玩转Sentinel定义异常-整合Open-Feign)(1)

sentinel上下文配置(玩转Sentinel定义异常-整合Open-Feign)(2)

流控测试

sentinel上下文配置(玩转Sentinel定义异常-整合Open-Feign)(3)

sentinel上下文配置(玩转Sentinel定义异常-整合Open-Feign)(4)

新版Sentinel整合OpenFeign配置实战
  • 加⼊依赖

<dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId> </dependency>

  • 开启Feign对Sentinel的⽀持

#开启Feign对Sentinel的支持 feign: sentinel: enabled: true

  • 创建容错类, 实现对应的服务接⼝, 记得加注解

@Service public class VideoServiceFallback implements VideoService { @Override public Video findById(int videoId) { Video video = new Video(); video.setTitle("系统默认数据!"); return video; } @Override public int save(Video video) { return 0; } }

  • 配置feign容错类

@FeignClient(name = "alibaba-video",fallback = VideoServiceFallback.class)

  • 测试

sentinel上下文配置(玩转Sentinel定义异常-整合Open-Feign)(5)

参考源码:alibaba-cloud: alibaba-cloud学习

参考原文:cyz

,

免责声明:本文仅代表文章作者的个人观点,与本站无关。其原创性、真实性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容文字的真实性、完整性和原创性本站不作任何保证或承诺,请读者仅作参考,并自行核实相关内容。文章投诉邮箱:anhduc.ph@yahoo.com

    分享
    投诉
    首页