在之前的老版本中,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 #自定義