忽略异常:
通过@HystrixCommand的参数配置我们可以忽略异常,不走降级方法正常返回异常信息。
自定义异常:
package com.example.springcloud.testdemo.exception;
/**
* Created by py
* 2020/3/25
*/
public class HystrixIgnoreException extends RuntimeException{
private String message;
public HystrixIgnoreException(String message) {
this.message = message;
}
}
ignoreExceptions:忽略指定异常
@Override
//我们指定忽略HystrixIgnoreException异常,即出现这个异常不走降级方法。
@HystrixCommand(fallbackMethod = "sendFail",ignoreExceptions={HystrixIgnoreException.class})
public String hystrixRestTemplateSend(String body) {
String url = "http://test1/eureka-clinet1/hystrixRestTemplate/Code";
//下面是故意跑出异常代码
try {
int i = 1/0;
} catch (Exception e) {
//设置 ignoreExceptions = HystrixIgnoreException.class,抛出此异常时不走熔断机制,直接返回异常信息
throw new HystrixIgnoreException("熔断忽略的异常,忽略属性设置");
}
return "test";
}
请求结果:
更换一个未被忽略的异常:
try {
int i = 1/0;
} catch (Exception e) {
//抛出 ignoreExceptions 中没有设置此异常,抛出该异常时触发熔断机制
throw new RuntimeException("熔断忽略的异常,继承HystrixBadRequestException");
}
请求结果:
是否启用降级方法:fallback.enabled
//fallback.enabled:启用降级方法(默认启用:true,false:直接返回异常)
//ignoreExceptions优先级高于fallback.enabled
@HystrixCommand(fallbackMethod = "sendFail",
ignoreExceptions={HystrixIgnoreException.class},
commandProperties={
@HystrixProperty(name = "fallback.enabled",value = "false")
})
public String hystrixRestTemplateSend(String body) {
//因为fallback.enabled是false,所以不会走fallback方法(降级),会直接返回异常
try {
int i = 1/0;
} catch (Exception e) {
// TODO: handle exception
throw new RuntimeException("熔断忽略的异常,继承HystrixBadRequestException");
}
}
请求返回:
更改抛出异常:
fallback.enabled=true:启用降级
ignoreExceptions={HystrixIgnoreException.class}:指定忽略降级的异常
@HystrixCommand(fallbackMethod = "sendFail",
ignoreExceptions={HystrixIgnoreException.class},
commandProperties={
@HystrixProperty(name = "fallback.enabled",value = "true")
})
public String hystrixRestTemplateSend(String body) {
String url = "http://test1/eureka-clinet1/hystrixRestTemplate/Code";
//下面是故意跑出异常代码
try {
int i = 1/0;
} catch (Exception e) {
//设置 ignoreExceptions = HystrixIgnoreException.class,抛出此异常时不走熔断机制,直接返回异常信息
throw new HystrixIgnoreException("熔断忽略的异常,忽略属性设置");
}
return "test";
}
返回信息:
总结:ignoreExceptions指定异常与fallback.enabled=true同时存在时ignoreExceptions优先级更高,因此不走fallback方法。