zoukankan      html  css  js  c++  java
  • Hystrix【异常机制处理】

    在之前的老版本中,feign中是默认开启hystrix的,从新版本中默认已经关闭了,如果要通过FeignClient调用服务并开启hystrix的话,需要自定义开启,即:feign.hystrix.enabled=true。

    在hystrix中,有5种异常会被fallback:

    • FAILURE:执行失败,抛出异常。
    • TIMEOUT:执行超时。
    • SHORT_CIRCUITED:断路器打开。
    • THREAD_POOL_REJECTED:线程池拒绝。
    • SEMAPHORE_REJECTED:信号量拒绝。

    有一种异常是不会触发fallback的,并且也不会被熔断,它是BAD_REQUEST,但是它会跑出HystrixBadRequestException,这种异常一般对应的是由非法参数或者一些非系统异常引起的,对于这种异常,可以根据响应创建对应的异常进行异常封装或者直接处理。

    在使用@FeignClient调用的时候,如果调用服务接口有4XX异常,可以使用ErrorDecoder进行包装,例如:

    import java.io.IOException;
    
    import org.springframework.stereotype.Component;
    
    import com.netflix.hystrix.exception.HystrixBadRequestException;
    
    import feign.Response;
    import feign.Util;
    
    @Component
    public class FeignErrorDecoder implements feign.codec.ErrorDecoder{
    
        @Override
        public Exception decode(String methodKey, Response response) {
         try {
                if (response.status() >= 400 && response.status() <= 499) {
                    String error = Util.toString(response.body().asReader());
                    return new HystrixBadRequestException(error);
                }
            } catch (IOException e) {
               System.out.println(e);
            }
            return feign.FeignException.errorStatus(methodKey, response);
        }
        
    }
    feign:
      hystrix:
        enabled: true
      client:
        config:
          user-client: #调用的服务名称
            errorDecoder: cn.springcloud.book.ex.service.dataservice.FeignErrorDecoder #自定义
  • 相关阅读:
    BZOJ4416 [Shoi2013]阶乘字符串 【序列自动机 + 状压dp】
    BZOJ2159 Crash 的文明世界 【第二类斯特林数 + 树形dp】
    快速求原根
    BZOJ2530 [Poi2011]Party 【贪心】
    BZOJ2213 [Poi2011]Difference 【乱搞】
    BZOJ2276 [Poi2011]Temperature 【单调队列】
    多项式除法
    loj2538 「PKUWC2018」Slay the Spire 【dp】
    loj2537 「PKUWC2018」Minimax 【概率 + 线段树合并】
    Java多线程之线程的暂停
  • 原文地址:https://www.cnblogs.com/idoljames/p/11716186.html
Copyright © 2011-2022 走看看