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提供了更优雅的服务调用方式,就是 ...
随机推荐
- 使用 Spring 访问 Hibernate 的方法有哪些?
我们可以通过两种方式使用 Spring 访问 Hibernate: 1. 使用 Hibernate 模板和回调进行控制反转 2. 扩展 HibernateDAOSupport 并应用 AOP 拦截器节 ...
- 什么是 Spring beans?
Spring beans 是那些形成 Spring 应用的主干的 java 对象.它们被 Spring IOC 容器初始化,装配,和管理.这些 beans 通过容器中配置的元数据创建.比如, 以 XM ...
- 5. Git初始化及仓库创建和操作
4. Git初始化及仓库创建和操作 基本信息设置 1. 设置用户名 git config --global user.name 'itcastphpgit1' 2. 设置用户名邮箱 git confi ...
- 如何将Matlab中“模糊控制设计器”的隶属度函数导出图片(figure)
如何将Matlab中"模糊控制设计器"的隶属度函数导出图片(figure)详情参考matlab官方帮助手册:plotmf()函数https://www.mathworks.com/ ...
- Python3通过字符串访问与修改局部变量
技术背景 在Python中定义一个函数时,就会把变量空间划分为全局变量(global)与局部变量(local),如果是定义在一个类的成员函数中,那么就还有额外的成员变量(self)空间.那么,如果在实 ...
- JavaScript读取剪贴板中的表格生成图片
原文 JavaScript读取剪贴板中的表格生成图片 演示地址 你可以访问下面的地址体验每个demo https://fairyever.github.io/excel-to-image-demo/ ...
- 深入理解ES6(二)(解构赋值)
变量的解构赋值 (1) 数组的解构赋值 1.基本用法 ES6 允许按照一定模式,从数组和对象中提取值,对变量进行赋值,这被称为解构(Destructuring ). 只要等号两边的模式相同,左边的变量 ...
- java基础-字符流
字符流 * 字符流是可以直接读写字符的IO流 * 字符流读取字符, 就要先读取到字节数据, 然后转为字符. 如果要写出字符, 需要把字符转为字节再写出. FileReader * FileRea ...
- jboss修改内存
在修改配置文件,在 <JBOSS_HOME> /bin/stadalone.conf中 找到并修改 如图
- victoriaMetrics库之布隆过滤器
victoriaMetrics库之布隆过滤器 代码路径:/lib/bloomfilter 概述 victoriaMetrics的vmstorage组件会接收上游传递过来的指标,在现实场景中,指标或瞬时 ...