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
Spring Cloud Feign+Hystrix自定义异常处理的更多相关文章
- 笔记:Spring Cloud Feign Hystrix 配置
在 Spring Cloud Feign 中,除了引入了用户客户端负载均衡的 Spring Cloud Ribbon 之外,还引入了服务保护与容错的工具 Hystrix,默认情况下,Spring Cl ...
- Spring Cloud Feign 如何使用对象参数
概述 Spring Cloud Feign 用于微服务的封装,通过接口代理的实现方式让微服务调用变得简单,让微服务的使用上如同本地服务.但是它在传参方面不是很完美.在使用 Feign 代理 GET 请 ...
- Spring Cloud中Hystrix、Ribbon及Feign的熔断关系是什么?
导读 今天和大家聊一聊在Spring Cloud微服务框架实践中,比较核心但是又很容易把人搞得稀里糊涂的一个问题,那就是在Spring Cloud中Hystrix.Ribbon以及Feign它们三者之 ...
- Spring Cloud Feign 自定义配置(重试、拦截与错误码处理) 实践
Spring Cloud Feign 自定义配置(重试.拦截与错误码处理) 实践 目录 Spring Cloud Feign 自定义配置(重试.拦截与错误码处理) 实践 引子 FeignClient的 ...
- Spring cloud Feign 深度学习与应用
简介 Spring Cloud Feign是一个声明式的Web Service客户端,它的目的就是让Web Service调用更加简单.Feign提供了HTTP请求的模板,通过编写简单的接口和插入注解 ...
- 微服务实战SpringCloud之Spring Cloud Feign替代HTTP Client
简介 在项目中我们有时候需要调用第三方的API,微服务架构中这种情况则更是无法避免--各个微服务之间通信.比如一般的项目中,有时候我们会使用 HTTP Client 发送 HTTP 请求来进行调用,而 ...
- spring cloud --- Feign --- 心得
spring boot 1.5.9.RELEASE spring cloud Dalston.SR1 1.前言 什么是Feign? 为了简化我们的开发,Spring Cloud Fei ...
- 第六章:声明式服务调用:Spring Cloud Feign
Spring Cloud Feign 是基于 Netflix Feign 实现的,整合了 Spring Cloud Ribbon 和 Spring Cloud Hystrix,除了提供这两者的强大功能 ...
- 微服务架构之spring cloud feign
在spring cloud ribbon中我们用RestTemplate实现了服务调用,可以看到我们还是需要配置服务名称,调用的方法 等等,其实spring cloud提供了更优雅的服务调用方式,就是 ...
随机推荐
- DateFormat类,利用SimpleDateFormat解决系统时间初始(格式化/解析)问题
目标: java.text.DateFormat 是日期/时间格式化子类的抽象类,我们通过这个类可以帮我们完成日期和文本之间的转换,也就是可以在Date对象与String对象之间进行来回转换. 格式化 ...
- 智能指针中C++重载'->'符号是怎么实现的
例如下面的代码: class StrPtr{ public: StrPtr() : _ptr(nullptr){} //拷贝构造函数等省略... std::string* operator->( ...
- 【控制】模型预测控制 MPC 【合集】Model Predictive Control
1.模型预测控制--运动学模型 2.模型预测控制--模型线性化 3.模型预测控制--模型离散化 4.模型预测控制--预测 5.模型预测控制--控制律优化二次型优化 6.模型预测控制--反馈控制 7.模 ...
- 顺利通过EMC实验(17)
- for 循环详解
学习目标: 掌握 for 循环的使用 学习内容: 1.for语法 for(初始化语句; boolean表达式; 循环后操作语句) { 循环体; } 流程图如下: 特点: 初始化语句:只在循环开始时执行 ...
- 适配手机端rpx像素
<script src="static/js/adaptive.js"></script> <script type="text/javas ...
- C# 将PDF转为Excel
通常,PDF格式的文档能支持的编辑功能不如office文档多,针对PDF文档里面有表格数据的,如果想要编辑表格里面的数据,可以将该PDF文档转为Excel格式,然后编辑.本文,将以C#代码为例,介绍如 ...
- MySQL存储引擎、基础数据类型、约束条件
MySQL存储引擎 存储引擎 # 存储引擎可以堪称是处理数据的不同方式 # 查看存储引擎的方式 show engines; # 需要掌握的四个存储引擎 MyISAM MySQL5.5之前的默认的存储引 ...
- Vue 中 axios 跨域配置 (!!!配置完成需要重新运行,不然也不起作用)
当拿到一个网址如:https://music.163.com/store/api/categorypage/list 获取数据是出现如下: 证明该网址不能非常直观的拿到数据.接下来我们试试跨域拿这个 ...
- OV5640图像采集(一)VGA显示
vga控制器模块 1 引言 项目的背景是采集无人车间现场的工件图像并送往控制间pc端处理,最终实现缺陷检测.项目包括图像采集模块,数据传输模块,上位机,缺陷检测算法等四个部分.其中,图像采集模块又分 ...