探讨通过Feign配合Hystrix进行调用时异常的处理

简介: 探讨通过Feign配合Hystrix进行调用时异常的处理

前言

  • 此文所述处理方式为本人在实践过程中研究分析得出的一种解决方案。
  • 本文不仅希望能为 SC 学习者提供一种如题问题的一种解决方案,并且希望通过本文引出各位 SC 的朋友对如题问题的共同探讨和最佳实践方案的分享。

场景及痛点

  • 单个项目是通过 Jersey 来实现 restful 风格的架构
  • 发生异常时异常信息总是提示没有回调方法,不能显示基础服务抛出的异常信息
  • 暂时没有考虑发生异常之后进行回调返回特定内容
  • 业务系统通过 feign 调用基础服务,基础服务是会根据请求抛出各种请求异常的(采用标准http状态码),现在我的想法是如果调用基础服务时发生请求异常,业务系统返回的能够返回基础服务抛出的状态码
  • 当然基础服务抛出的请求异常不能触发 hystrix 的熔断机制

问题解决方案分析

解决思路

  • 通过网上一些资料的查询,看到很多文章会说 HystrixBadRequestException 不会触发 hystrix 的熔断 –> 但是并没有介绍该异常的实践方案
  • 感觉要解决项目的痛点,切入点应该就在 HystrixBadRequestException 了。于是先看源码,一方面对 Hystrix 加深理解,尝试理解作者设计的初衷与想法,另一方面看看是否能找到其他方案达到较高的实践标准

对应源码解释对应方案

主要类对象简介

  • interface UserRemoteCall 定义feign的接口其上会有 @FeignClient,FeignClient 定义了自己的 Configuration –> FeignConfiguration
  • class FeignConfiguration 这里是定义了指定 Feign 接口使用的自定义配置,如果不想该配置成为全局配置,不要让该类被自动扫描到
  • class UserErrorDecoder implements ErrorDecoder 该类会处理响应状态码 (![200,300) || !404)

不使用Hystrix

源码分析
  • Feign 的默认配置在 org.springframework.cloud.netflix.feign.FeignClientsConfiguration 类中,如果不自定义Feign.Builder,会优先配置 feign.hystrix.HystrixFeign.Builder extends Feign.Builder,该类会让 Feign 的内部调用受到 Hystrix 的控制

//省略部分代码
    @Configuration
    @ConditionalOnClass({ HystrixCommand.class, HystrixFeign.class })
    protected static class HystrixFeignConfiguration {
        @Bean
        @Scope("prototype")
        @ConditionalOnMissingBean
        @ConditionalOnProperty(name = "feign.hystrix.enabled", matchIfMissing = true)
        public Feign.Builder feignHystrixBuilder() {
        return HystrixFeign.builder();
        }
    }
解决方案
  • 当然不使用 Hystrix 就不会有熔断等问题出现,处理好 ErrorDecoder.decode() 即可。
  • 不开启 Hystrix 的方式:
  1. 配置增加 feign.hystrix.enabled=false ,这会在全局生效不推荐。
  2. FeignConfiguration 增加:(推荐)

@Bean
@Scope("prototype")
public Feign.Builder feignBuilder() {
    return Feign.builder();
}

使用 Hystrix 解决内部调用抛出异常问题

源码分析
  • Hystrix 的设计方案是通过命令模式加 RxJava 实现的观察者模式来开发的,想完全熟悉 Hystrix 的运作流程需要熟练掌握 RxJava,本文只对源码进行简单介绍,后面有时间有机会再详细介绍
  • Hystrix如何处理异常的 代码位置:com.netflix.hystrix.AbstractCommand#executeCommandAndObserve
 //省略部分代码
 private Observable<R> executeCommandAndObserve(final AbstractCommand<R> _cmd) {
//省略部分代码
        final Func1<Throwable, Observable<R>> handleFallback = new Func1<Throwable, Observable<R>>() {
            @Override
            public Observable<R> call(Throwable t) {
                Exception e = getExceptionFromThrowable(t);
                executionResult = executionResult.setExecutionException(e);
                if (e instanceof RejectedExecutionException) {
                    return handleThreadPoolRejectionViaFallback(e);
                } else if (t instanceof HystrixTimeoutException) {
                    return handleTimeoutViaFallback();
                } else if (t instanceof HystrixBadRequestException) {
                    return handleBadRequestByEmittingError(e);
                } else {
                    /*
                     * Treat HystrixBadRequestException from ExecutionHook like a plain HystrixBadRequestException.
                     */
                    if (e instanceof HystrixBadRequestException) {
                        eventNotifier.markEvent(HystrixEventType.BAD_REQUEST, commandKey);
                        return Observable.error(e);
                    }
                    return handleFailureViaFallback(e);
                }
            }
        };
//省略部分代码
    }

该类中该方法为发生异常的回调方法,由此可以看出如果抛出异常如果是 HystrixBadRequestException 是直接处理异常之后进行抛出(这里不会触发熔断机制),而不是进入回调方法。

解决方案

那么我们对于请求异常的解决方案就需要通过 HystrixBadRequestException 来解决了(不会触发熔断机制),根据返回响应创建对应异常并将异常封装进 HystrixBadRequestException,业务系统调用中取出 HystrixBadRequestException 中的自定义异常进行处理,封装异常说明:

public class UserErrorDecoder implements ErrorDecoder{
  private Logger logger = LoggerFactory.getLogger(getClass());
  public Exception decode(String methodKey, Response response) {
    ObjectMapper om = new JiaJianJacksonObjectMapper();
    JiaJianResponse resEntity;
    Exception exception = null;
        try {
      resEntity = om.readValue(Util.toString(response.body().asReader()), JiaJianResponse.class);
//为了说明我使用的 WebApplicationException 基类,去掉了封装
            exception = new WebApplicationException(javax.ws.rs.core.Response.status(response.status()).entity(resEntity).type(MediaType.APPLICATION_JSON).build());
    } catch (IOException ex) {
      logger.error(ex.getMessage(), ex);
    }
    // 这里只封装4开头的请求异常
    if (400 <= response.status() || response.status() < 500){
      exception = new HystrixBadRequestException("request exception wrapper", exception);
    }else{
      logger.error(exception.getMessage(), exception);
    }
    return exception;
  }
}

为 Feign 配置 ErrorDecoder

@Configuration
public class FeignConfiguration {
  @Bean
  public ErrorDecoder errorDecoder(){
    return new UserErrorDecoder();
  }
}

业务系统处理异常说明:

 @Override
    public UserSigninResEntity signIn(UserSigninReqEntity param) throws Exception {
    try {
//省略部分代码
        UserSigninResEntity entity = userRemoteCall.signin(secretConfiguration.getKeys().get("user-service"), param);
//省略部分代码
    } catch (Exception ex) {
        logger.error(ex.getMessage(), ex);
//这里进行异常处理
        if(ex.getCause() instanceof WebApplicationException){
            throw (WebApplicationException) ex.getCause();
        }
            throw ex;
        }
    }

WebApplicationExceptionjavax.ws.rs 包中异常,通过 Jersey 抛出该异常能够将返回的 HttpCode 封装进该异常中(上述代码中展示了如何封装 HttpCode),抛出该异常,调用端就能得到返回的 HttpCode。

总结

  • 本文主要出发点在于如何解决在 Feign 中使用 Hystrix 时被调用端抛出请求异常的问题。
  • 本项目使用 Jersey,封装 WebApplicationException 即可满足需求,其他架构也是大同小异了。
  • 该解决方案我不确定是否为最佳实践方案,特别希望和欢迎有不同想法或意见的朋友来与我交流,包括但不限于解决方案、项目痛点是否合理等等。
目录
相关文章
|
9月前
SpringCloud极简入门-Feign开启Hystrix
1.支付服务集成Hystrix 官方文档:https://cloud.spring.io/spring-cloud-static/Greenwich.SR5/single/spring-cloud.html#spring-cloud-feign-hystrix 支付服务 springcloud-pay-server-1040 之前集成了Feign,修改该工程集成Hystrix。我们除了要给Feign开启Hystrix以外还需要为Feign接口编写托底类。
103 0
|
8月前
Ribbon、Feign、Hystrix超时&重试&熔断问题
在使用Ribbon、Feign、Hystrix组合时,因为配置的问题出现以下现象,让我的大脑CPU烧的不行不行(拿我老家话说就是“脑子ran滴奥”)
103 0
|
6月前
|
Java Spring
15SpringCloud - 断路器项目示例(Feign Hystrix)
15SpringCloud - 断路器项目示例(Feign Hystrix)
19 0
|
9月前
|
负载均衡 Java Linux
springCloud搭建、zuul、feign、hystrix、ribbon(内部培训)
springCloud搭建、zuul、feign、hystrix、ribbon(内部培训)
127 0
springCloud搭建、zuul、feign、hystrix、ribbon(内部培训)
|
10月前
|
缓存 负载均衡 监控
Spring Cloud 五大组件 简介 Eureka、Ribbon、Hystrix、Feign和Zuul
Spring Cloud 五大组件 简介 Eureka、Ribbon、Hystrix、Feign和Zuul
1023 0
|
10月前
|
缓存 负载均衡 监控
springboot不香吗?为什么还要使用springcloud--各个组件基本介绍(Feign,Hystrix,ZUUL)
springboot不香吗?为什么还要使用springcloud--各个组件基本介绍(Feign,Hystrix,ZUUL)
65 0
|
存储 负载均衡 Java
Springboot 整合 SpringCloud组件-Feign(Ribbon/Hystrix) (三)
Springboot 整合 SpringCloud组件-Feign(Ribbon/Hystrix) (三)
391 0
Springboot 整合 SpringCloud组件-Feign(Ribbon/Hystrix) (三)
|
负载均衡 API 网络架构
SpringCloudNetflix之Hystrix(熔断器)、Zull(网关)、Feign完整使用(三)
SpringCloudNetflix之Hystrix(熔断器)、Zull(网关)、Feign完整使用(三)
240 0
SpringCloudNetflix之Hystrix(熔断器)、Zull(网关)、Feign完整使用(三)
|
网络架构 微服务
SpringCloudNetflix之Hystrix(熔断器)、Zull(网关)、Feign完整使用(二)
SpringCloudNetflix之Hystrix(熔断器)、Zull(网关)、Feign完整使用(二)
121 0
SpringCloudNetflix之Hystrix(熔断器)、Zull(网关)、Feign完整使用(二)