默认降级返回数据问题
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 {
//降级业务处理
}
}
异常种类
【新版】实现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));
}
}
降级测试
流控测试
<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)
参考源码:alibaba-cloud: alibaba-cloud学习
参考原文:cyz