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提供了更优雅的服务调用方式,就是 ...
随机推荐
- 为什么 redis 需要把所有数据放到内存中?
答Redis 为了达到最快的读写速度将数据都读到内存中,并通过异步的方式将数 据写入磁盘.所以 redis 具有快速和数据持久化的特征.如果不将数据放在内存中, 磁盘 I/O 速度为严重影响 redi ...
- Python - random库介绍
- 遇到的问题之“解决tomcat中文乱码问题”
方案1:在server.xml中添加了 URIEncoding="UTF-8" 属性 路径:C:\stop\apache-tomcat-8.5.69\conf 修改内容 如若方案1 ...
- 什么是RESTFUL?REST的请求方法有哪些,有什么区别?
这里是修真院前端小课堂,每篇分享文从 [背景介绍][知识剖析][常见问题][解决方案][编码实战][扩展思考][更多讨论][参考文献] 八个方面深度解析前端知识/技能,本篇分享的是: [什么是REST ...
- PAT B1015德才论
题目描述: 宋代史学家司马光在<资治通鉴>中有一段著名的"德才论":"是故才德全尽谓之圣人,才德兼亡谓之愚人,德胜才谓之君子,才胜德谓之小人.凡取人之术,苟不 ...
- IDEA个人常用快捷键
Ctrl+Z:撤销 Ctrl+Shift+Z:重做 Ctrl+X:剪贴 Ctrl+C:复制 Ctrl+V:粘贴 Ctrl+Y:删除当前行 Ctrl+D:复制当前行 Alt+向左箭头:返回上次光标位置 ...
- 解决IDEA中控制台输出乱码
1. 修改VM Options(2种方法) 第一种,直接修改Tomcat中的 VM Options,这种只对当前项目有效 (1)先点击 Run -> Edit Configurations- 2 ...
- caioj 1000: [视频]整数运算[水题]
题目大意:输入两个整数a和b,输出他们的和. 题解:水题不用题解,简单看一下就知道了-- 代码: #include <cstdio> int a, b; int main() { whil ...
- Spring Boot配置文件加载顺序
提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档 文章目录 前言 一.通过spring.config.location改变配置文件的位置 二.外部配置加载顺序 1.使用命令行参数指定加 ...
- Mybatis更新和删除数据
接上文->Mybatis快速入门<- 1.在UserMapper.xml配置更新和删除 <!-- 更新操作--> <update id="update" ...