如何配置Hystrix使其针对404等特定错误码不开启熔断
Hystrix针对特定HTTP错误码不触发熔断的配置方案
核心逻辑:Hystrix默认会将所有请求异常计入服务失败统计,触发熔断逻辑。可以通过自定义Feign错误解码器,将不需要触发熔断的错误码对应的异常转换为Hystrix原生忽略的异常类型,排除这类请求的熔断计数。
步骤1:自定义Feign错误解码器
Hystrix原生默认不会将HystrixBadRequestException及其子类判定为服务故障,不会纳入失败请求统计、也不会触发降级和熔断。我们可以在错误解码器中将指定错误码(如404)的请求直接抛出该异常:
import com.netflix.hystrix.exception.HystrixBadRequestException; import feign.Response; import feign.codec.ErrorDecoder; import org.springframework.http.HttpStatus; public class CustomFeignErrorDecoder implements ErrorDecoder { private final ErrorDecoder defaultDecoder = new ErrorDecoder.Default(); @Override public Exception decode(String methodKey, Response response) { // 匹配不需要触发熔断的错误码 if (response.status() == HttpStatus.NOT_FOUND.value()) { return new HystrixBadRequestException("请求资源不存在:" + response.request().url()); } // 其他错误走默认逻辑,正常计入熔断统计 return defaultDecoder.decode(methodKey, response); } }
步骤2:注册自定义错误解码器
将自定义的错误解码器声明为Spring Bean,Feign会自动加载使用:
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class FeignGlobalConfig { @Bean public ErrorDecoder customFeignErrorDecoder() { return new CustomFeignErrorDecoder(); } }
可选配置:批量忽略客户端错误码
如果需要将所有4xx类客户端错误都排除在熔断统计外,只需要修改解码器的判断逻辑即可:
@Override public Exception decode(String methodKey, Response response) { // 所有4xx客户端错误都不触发熔断 if (response.status() >= 400 && response.status() < 500) { return new HystrixBadRequestException("客户端请求错误,状态码:" + response.status()); } return defaultDecoder.decode(methodKey, response); }
效果验证
配置完成后,批量发起返回404的请求,Hystrix的失败请求计数不会增长,熔断器不会打开;5xx类服务端错误依然会正常触发熔断逻辑,不影响原有故障保护能力。
内容的提问来源于stack exchange,提问作者David Manzano
相关产品推荐
相关产品推荐

