开启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,二选一:

  1. 在client中指定
@FeignClient(name = "service-name",
fallbackFactory = TestServiceFallback.class,
configuration = {NotBreakerConfiguration.class})
public interface TestService {
// 省略
}
  1. 在配置文件中指定
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自定义异常处理的更多相关文章

  1. 笔记:Spring Cloud Feign Hystrix 配置

    在 Spring Cloud Feign 中,除了引入了用户客户端负载均衡的 Spring Cloud Ribbon 之外,还引入了服务保护与容错的工具 Hystrix,默认情况下,Spring Cl ...

  2. Spring Cloud Feign 如何使用对象参数

    概述 Spring Cloud Feign 用于微服务的封装,通过接口代理的实现方式让微服务调用变得简单,让微服务的使用上如同本地服务.但是它在传参方面不是很完美.在使用 Feign 代理 GET 请 ...

  3. Spring Cloud中Hystrix、Ribbon及Feign的熔断关系是什么?

    导读 今天和大家聊一聊在Spring Cloud微服务框架实践中,比较核心但是又很容易把人搞得稀里糊涂的一个问题,那就是在Spring Cloud中Hystrix.Ribbon以及Feign它们三者之 ...

  4. Spring Cloud Feign 自定义配置(重试、拦截与错误码处理) 实践

    Spring Cloud Feign 自定义配置(重试.拦截与错误码处理) 实践 目录 Spring Cloud Feign 自定义配置(重试.拦截与错误码处理) 实践 引子 FeignClient的 ...

  5. Spring cloud Feign 深度学习与应用

    简介 Spring Cloud Feign是一个声明式的Web Service客户端,它的目的就是让Web Service调用更加简单.Feign提供了HTTP请求的模板,通过编写简单的接口和插入注解 ...

  6. 微服务实战SpringCloud之Spring Cloud Feign替代HTTP Client

    简介 在项目中我们有时候需要调用第三方的API,微服务架构中这种情况则更是无法避免--各个微服务之间通信.比如一般的项目中,有时候我们会使用 HTTP Client 发送 HTTP 请求来进行调用,而 ...

  7. spring cloud --- Feign --- 心得

    spring boot      1.5.9.RELEASE spring cloud    Dalston.SR1 1.前言 什么是Feign? 为了简化我们的开发,Spring Cloud Fei ...

  8. 第六章:声明式服务调用:Spring Cloud Feign

    Spring Cloud Feign 是基于 Netflix Feign 实现的,整合了 Spring Cloud Ribbon 和 Spring Cloud Hystrix,除了提供这两者的强大功能 ...

  9. 微服务架构之spring cloud feign

    在spring cloud ribbon中我们用RestTemplate实现了服务调用,可以看到我们还是需要配置服务名称,调用的方法 等等,其实spring cloud提供了更优雅的服务调用方式,就是 ...

随机推荐

  1. centos7 环境安装rabbitmq 集群

    继上一篇https://www.cnblogs.com/drafire/p/10062891.html ,这篇博客继续介绍centos 7下安装rabbitmq的集群. 今天在公司搞了一天的rabbi ...

  2. 记一次 Nuxt 3 在 Windows 下的打包问题

    0. 背景 之前用 Nuxt 3 写了公司的官网,包括了样式.字体图标.图片.视频等,其中样式和字体图标放在了 assets/styles 和 assets/fonts 目录下,而图片和视频则放在了 ...

  3. pandas数据读取

    02. Pandas读取数据 本代码演示: pandas读取纯文本文件 读取csv文件 读取txt文件 pandas读取xlsx格式excel文件 pandas读取mysql数据表 1.读取纯文本文件 ...

  4. 编译器警告c4996

    由于编译器的原因(我用的是vs 2012),我们写程序时有时候会遇到编译器给出的警告,如: warning C4996: 'fopen': This function or variable may ...

  5. Pycharm使用 Ctrl+滚轮 调整字体大小

    首先,打开File中的Settings 然后,点开Editor内的General 最后,在3 指向的位置勾选:Change font size (Zoom)with Ctrl+Mouse Whel 这 ...

  6. Slog71_选取、上传和显示本地图片GET !(微信小程序之云开发-全栈时代3)

    ArthurSlog SLog-71 Year·1 Guangzhou·China Sep 12th 2018 ArthurSlog Page GitHub NPM Package Page 掘金主页 ...

  7. Html5 Canvas学习之路(五)

    Canvas 图像(上) Canvas 图像API可以加载图像数据,然后直接将图像应用到画布上.还可以裁切.拼贴图像数据,以显示用户需要的部分.此外,Canvas还提供了像素数据的存储功能,这样就能对 ...

  8. java中方法重载是什么, 实际中到底有什么意义, 用处?请举例

    7.3 方法重载(overload)  当几个方法有相同的方法名,但参数个数不同或参数类型不同时,就涉及方法重载 方法重载有什么意义呢?在公司里编程,有时候一个方法名,要用到很多次,而且每次跟每次的参 ...

  9. Java重载容易引发的错误—返回类型

    方法的签名仅仅与方法名和参数类型相关,而与访问控制符.返回类型无关,以及方法体中的内容都没有关系,下面用一个例子说明; 如果Student类两种签名,myStudent(int,int)返回int 类 ...

  10. Spring-级联赋值

    一.级联赋值第一种方法 1.创建Emp类 package com.bean; public class Emp { private String EName; private String gende ...