擴充套件Spring Cloud Feign 實現自動降級

weixin_33766168發表於2019-02-22

自動降級目的

在Spring Cloud 使用feign 的時候,需要明確指定fallback 策略,不然會提示錯誤
先來看預設的feign service 是要求怎麼做的。feign service 定義一個 factory 和 fallback 的類

@FeignClient(value = ServiceNameConstants.UMPS_SERVICE, fallbackFactory = RemoteLogServiceFallbackFactory.class)
public interface RemoteLogService {}

但是我們大多數情況的feign 降級策略為了保證冪等都會很簡單,輸出錯誤日誌即可。
類似如下程式碼,在企業中開發非常不方便

@Slf4j
@Component
public class RemoteLogServiceFallbackImpl implements RemoteLogService {
    @Setter
    private Throwable cause;


    @Override
    public R<Boolean> saveLog(SysLog sysLog, String from) {
        log.error("feign 插入日誌失敗", cause);
        return null;
    }
}

自動降級效果

@FeignClient(value = ServiceNameConstants.UMPS_SERVICE)
public interface RemoteLogService {}
  • Feign Service 完成同樣的降級錯誤輸出
  • FeignClient 中無需定義無用的fallbackFactory
  • FallbackFactory 也無需註冊到Spring 容器中

程式碼變化,去掉FeignClient 指定的降級工廠

程式碼變化,刪除降級相關的程式碼

核心原始碼

  1. 注入我們個性化後的Feign
@Configuration
@ConditionalOnClass({HystrixCommand.class, HystrixFeign.class})
protected static class HystrixFeignConfiguration {
    @Bean
    @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    @ConditionalOnProperty("feign.hystrix.enabled")
    public Feign.Builder feignHystrixBuilder(FeignContext feignContext) {
        return PigxHystrixFeign.builder(feignContext)
                .decode404()
                .errorDecoder(new PigxFeignErrorDecoder());
    }
}
  1. 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);
}
  1. 構建feign 客戶端執行PigxHystrixInvocationHandler的增強
Feign build(@Nullable final FallbackFactory<?> nullableFallbackFactory) {
        super.invocationHandlerFactory((target, dispatch) ->
                new PigxHystrixInvocationHandler(target, dispatch, setterFactory, nullableFallbackFactory));
        super.contract(new HystrixDelegatingContract(contract));
        return super.build();
    }
  1. PigxHystrixInvocationHandler.getFallback() 獲取降級策略
    @Override
    @Nullable
    @SuppressWarnings("unchecked")
    protected Object getFallback() {
            // 如果 @FeignClient  沒有配置降級策略,使用動態代理建立一個
            if (fallbackFactory == null) {
                fallback = PigxFeignFallbackFactory.INSTANCE.create(target.type(), getExecutionException());
            } else {
              // 如果 @FeignClient配置降級策略,使用配置的
                fallback = fallbackFactory.create(getExecutionException());
            }
    }
  1. PigxFeignFallbackFactory.create 動態代理邏輯
    public T create(final Class<?> type, final Throwable cause) {
        return (T) FALLBACK_MAP.computeIfAbsent(type, key -> {
            Enhancer enhancer = new Enhancer();
            enhancer.setSuperclass(key);
            enhancer.setCallback(new PigxFeignFallbackMethod(type, cause));
            return enhancer.create();
        });
    }
  1. PigxFeignFallbackMethod.intercept, 預設的降級邏輯,輸出降級方法資訊和錯誤資訊,並且把錯誤格式
public Object 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 instanceof PigxFeignException ?
                ((PigxFeignException) cause).getResult() : R.builder()
                .code(CommonConstants.FAIL)
                .msg(cause.getMessage()).build();
        return result;
    }
    return null;
}

關注我們

相關文章