這篇文章主要講解了“Spring Cloud Feign怎么實現自動降級”,文中的講解內容簡單清晰,易于學習與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學習“Spring Cloud Feign怎么實現自動降級”吧!
自動降級目的
在Spring Cloud 使用feign 的時候,需要明確指定fallback 策略,不然會提示錯誤。先來看默認的feign service 是要求怎么做的。feign service 定義一個 factory 和 fallback 的類
@FeignClient(value =ServiceNameConstants.UMPS_SERVICE, fallbackFactory =RemoteLogServiceFallbackFactory.class)
publicinterfaceRemoteLogService{}
但是我們大多數情況的feign 降級策略為了保證冪等都會很簡單,輸出錯誤日志即可。類似如下代碼,在企業中開發非常不方便
@Slf4j
@Component
publicclassRemoteLogServiceFallbackImplimplementsRemoteLogService{
@Setter
privateThrowable cause;
@Override
public R<Boolean> saveLog(SysLog sysLog,Stringfrom){
log.error("feign 插入日志失敗", cause);
returnnull;
}
}
自動降級效果
@FeignClient(value =ServiceNameConstants.UMPS_SERVICE)
publicinterfaceRemoteLogService{}
Feign Service 完成同樣的降級錯誤輸出
FeignClient 中無需定義無用的fallbackFactory
FallbackFactory 也無需注冊到Spring 容器中
代碼變化,去掉FeignClient 指定的降級工廠
代碼變化,刪除降級相關的代碼
核心源碼
1. 注入我們個性化后的Feign
@Configuration
@ConditionalOnClass({HystrixCommand.class,HystrixFeign.class})
protectedstaticclassHystrixFeignConfiguration{
@Bean
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
@ConditionalOnProperty("feign.hystrix.enabled")
publicFeign.Builder feignHystrixBuilder(FeignContext feignContext){
returnPigxHystrixFeign.builder(feignContext)
.decode404()
.errorDecoder(newPigxFeignErrorDecoder());
}
}
2. PigxHystrixFeign.target 方法是根據@FeignClient 注解生成代理類的過程,注意注釋
@Override
public<T> T target(Target<T> target){
Class<T> targetType = target.type();
FeignClient feignClient =AnnotatedElementUtils.getMergedAnnotation(targetType,FeignClient.class);
String factoryName = feignClient.name();
SetterFactory setterFactoryBean =this.getOptional(factoryName, feignContext,SetterFactory.class);
if(setterFactoryBean !=null){
this.setterFactory(setterFactoryBean);
}
// 以下為獲取降級策略代碼,構建降級,這里去掉了降級非空的非空的校驗
Class<?> fallback = feignClient.fallback();
if(fallback !=void.class){
return targetWithFallback(factoryName, feignContext, target,this, fallback);
}
Class<?> fallbackFactory = feignClient.fallbackFactory();
if(fallbackFactory !=void.class){
return targetWithFallbackFactory(factoryName, feignContext, target,this, fallbackFactory);
}
return build().newInstance(target);
}
3. 構建feign 客戶端執行PigxHystrixInvocationHandler的增強
Feign build(@NullablefinalFallbackFactory<?> nullableFallbackFactory){
super.invocationHandlerFactory((target, dispatch)->
newPigxHystrixInvocationHandler(target, dispatch, setterFactory, nullableFallbackFactory));
super.contract(newHystrixDelegatingContract(contract));
returnsuper.build();
}
4. PigxHystrixInvocationHandler.getFallback() 獲取降級策略
@Override
@Nullable
@SuppressWarnings("unchecked")
protectedObject getFallback(){
// 如果 @FeignClient 沒有配置降級策略,使用動態代理創建一個
if(fallbackFactory ==null){
fallback =PigxFeignFallbackFactory.INSTANCE.create(target.type(), getExecutionException());
}else{
// 如果 @FeignClient配置降級策略,使用配置的
fallback = fallbackFactory.create(getExecutionException());
}
}
5. PigxFeignFallbackFactory.create 動態代理邏輯
public T create(finalClass<?> type,finalThrowable cause){
return(T) FALLBACK_MAP.computeIfAbsent(type, key ->{
Enhancer enhancer =newEnhancer();
enhancer.setSuperclass(key);
enhancer.setCallback(newPigxFeignFallbackMethod(type, cause));
return enhancer.create();
});
}
6. PigxFeignFallbackMethod.intercept, 默認的降級邏輯,輸出降級方法信息和錯誤信息,并且把錯誤格式
publicObject intercept(Object o,Method method,Object[] objects,MethodProxy methodProxy){
log.error("Fallback class:[{}] method:[{}] message:[{}]",
type.getName(), method.getName(), cause.getMessage());
if(R.class== method.getReturnType()){
final R result = cause instanceofPigxFeignException?
((PigxFeignException) cause).getResult(): R.builder()
.code(CommonConstants.FAIL)
.msg(cause.getMessage()).build();
return result;
}
returnnull;
}
感謝各位的閱讀,以上就是“Spring Cloud Feign怎么實現自動降級”的內容了,經過本文的學習后,相信大家對Spring Cloud Feign怎么實現自動降級這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是億速云,小編將為大家推送更多相關知識點的文章,歡迎關注!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。