Spring Cloud Feign+Hystrix自定义异常处理
开启Hystrix
spring-cloud-dependencies Dalston版本之后,默认Feign对Hystrix的支持默认是关闭的,需要手动开启。
feign.hystrix.enabled=true
开启hystrix,可以选择关闭熔断或超时。
关闭熔断:
# 全局关闭熔断:
hystrix.command.default.circuitBreaker.enabled: false
# 局部关闭熔断:
hystrix.command.<HystrixCommandKey>.circuitBreaker.enabled: false
设置超时:
# 全局设置超时:
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds: 1000
# 局部设置超时:
hystrix.command.<HystrixCommandKey>.execution.isolation.thread.timeoutInMilliseconds: 1000
关闭超时:
# 全局关闭:
hystrix.command.default.execution.timeout.enabled: false
# 局部关闭:
hystrix.command.<HystrixCommandKey>.execution.timeout.enabled: false
Fallback
fallback 是 Hystrix 命令执行失败时使用的后备方法,用来实现服务的降级处理逻辑。在 HystrixCommand 中可以通过重载 getFallback() 方法来实现服务降级逻辑,Hystrix 会在 run() 执行过程中出现错误、超时、线程池拒绝、短路熔断等情况时,执行 getFallback() 方法内的逻辑。
通常,当 HystrixCommand 的主方法(run()
) 中抛出异常时,便会触发 getFallback()。除了一个例外 —— HystrixBadRequestException。当抛出 HystrixBadRequestException
,不论当前 Command 是否定义了 getFallback(),都不会触发,而是向上抛出异常。
如果实现业务时有一些异常希望能够向上抛出,而不是触发 Fallback 策略,便可以封装到 HystrixBadRequestException
中。
getFallback() 的执行时间并不受 HystrixCommand 的超时时间的控制。
Feign对异常的封装
通过实现FallbackFactory
,可以在create
方法中获取到服务抛出的异常。但是请注意,这里的异常是被Feign
封装过的异常,不能直接在异常信息中看出原始方法抛出的异常。
1.自定义error decoder,不进入熔断,保留原始报错信息,向上层抛出的方法。
package test.config;
import com.alibaba.fastjson.JSONObject;
import com.netflix.hystrix.exception.HystrixBadRequestException;
import feign.Response;
import feign.Util;
import feign.codec.ErrorDecoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.io.IOException;
public class NotBreakerConfiguration {
@Bean
public ErrorDecoder errorDecoder() {
return new SpecialErrorDecoder();
}
/**
* 自定义错误
*/
public class SpecialErrorDecoder implements ErrorDecoder {
private Logger logger = LoggerFactory.getLogger(getClass());
@Override
public Exception decode(String methodKey, Response response) {
Exception exception = null;
try {
String json = Util.toString(response.body().asReader());
exception = new RuntimeException(json);
JsonResult result = JSONObject.parseObject(json, JsonResult.class);
// 业务异常包装成 HystrixBadRequestException,不进入熔断逻辑
if (!result.isSuccess()) {
exception = new HystrixBadRequestException(result.getMessage());
}
} catch (IOException ex) {
logger.error(ex.getMessage(), ex);
}
return exception;
}
}
}
2.为FeignClient指定error decoder,二选一:
- 在client中指定
@FeignClient(name = "service-name",
fallbackFactory = TestServiceFallback.class,
configuration = {NotBreakerConfiguration.class})
public interface TestService {
// 省略
}
- 在配置文件中指定
feign:
client:
config:
servive-name:
error-decoder: NotBreakerConfiguration
3.上层调用
package test;
import com.netflix.hystrix.exception.HystrixBadRequestException;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class TestServiceApi {
public void withdraw() {
try {
// 省略feign client方法调用
} catch (HystrixBadRequestException e) {
// 原始错误信息
log.info(e.getMessage());
} catch (Exception e) {
log.error("error", e);
}
}
}
参考:
https://blog.csdn.net/lvyuan1234/article/details/77155919
https://juejin.im/post/5bae37ca5188255c652d4c6a
https://my.oschina.net/xiaominmin/blog/2986631/print
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律