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 #自定义

 

    原文作者:KingJames、
    原文地址: https://www.cnblogs.com/idoljames/p/11716186.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞