<返回更多

玩转Sentinel⾃定 义异常-整合Open-Feign

2022-06-16    不凡的菠菜呀
加入收藏

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

默认降级返回数据问题

AlibabCloud版本升级,不兼容问题

⾃定义降级返回数据

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

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

异常种类

【新版】实现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⾃定 义异常-整合Open-Feign

 


玩转Sentinel⾃定 义异常-整合Open-Feign

 

流控测试

玩转Sentinel⾃定 义异常-整合Open-Feign

 


玩转Sentinel⾃定 义异常-整合Open-Feign

 

新版Sentinel整合OpenFeign配置实战

<dependency>
       <groupId>com.alibaba.cloud</groupId>
       <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
#开启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;
    }
}
@FeignClient(name = "alibaba-video",fallback = VideoServiceFallback.class)

 

玩转Sentinel⾃定 义异常-整合Open-Feign

 

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

参考原文:cyz

声明:本站部分内容来自互联网,如有版权侵犯或其他问题请与我们联系,我们将立即删除或处理。
▍相关推荐
更多资讯 >>>