zoukankan      html  css  js  c++  java
  • 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,二选一:

    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

  • 相关阅读:
    寿司点餐系统Sprint1总结
    寿司点餐系统一周总结
    对点餐APP现阶段开发的问题
    寿司点餐系统11.16
    Sprint
    R扩展包
    实验8 SQLite数据库操作
    实验7 BindService模拟通信
    实验6 在应用程序中播放音频和视频
    实验5 数独游戏界面设计
  • 原文地址:https://www.cnblogs.com/ylty/p/12004276.html
Copyright © 2011-2022 走看看