第十一章 Sentinel⾃定 义异常-整合Open-Feign

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

  • 实现BlockExceptionHandler并且重写handle⽅法

    @Component 
    public class XdclassUrlBlockHandler implements BlockExceptionHandler {
     @Override
     public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws Exception {
         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("contentType","application/json;charset=UTF-8");
    
         httpServletResponse.getWriter().write(JSON.toJSONString(backMap));
       }
     }
    
    
    
  • 使⽤Feign整合Sentinel配置
    引入依赖

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

    开启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 int saveVideo(Video video) {
         return 0;
     }
    }
    

    配置feign容错类

    @FeignClient(name="xdclass-video-service",fallback = VideoServiceFallback.class)
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值