当使用Spring cloud使用Feign、Hystrix相关技术时候,每个接口类使用@FeignClient
注解同时需要要指定fallbackFactory、或者fallback进行降级处理,有些时候我们需要一个统一的处理机制,不想写那么多的FallbackFactory。
我们的应用程序中通过引用注解@EnableFeignClients,其通过import导入FeignClientsRegistrar,该类会扫描classpath下面所有@FeignClient注解的接口并且注入到IOC容器,如下:
class FeignClientsRegistrar
implements ImportBeanDefinitionRegistrar, ResourceLoaderAware, EnvironmentAware {
// patterned after Spring Integration IntegrationComponentScanRegistrar
// and RibbonClientsConfigurationRegistgrar
// 其他省略代码...
public void registerFeignClients(AnnotationMetadata metadata,
BeanDefinitionRegistry registry) {
ClassPathScanningCandidateComponentProvider scanner = getScanner();
scanner.setResourceLoader(this.resourceLoader);
Set<String> basePackages;
Map<String, Object> attrs = metadata
.getAnnotationAttributes(EnableFeignClients.class.getName());
AnnotationTypeFilter annotationTypeFilter = new AnnotationTypeFilter(
FeignClient.class);
final Class<?>[] clients = attrs == null ? null
: (Class<?>[]) attrs.get("clients");
if (clients == null || clients.length == 0) {
scanner.addIncludeFilter(annotationTypeFilter);
basePackages = getBasePackages(metadata);
}
else {
final Set<String> clientClasses = new HashSet<>();
basePackages = new HashSet<>();
for (Class<?> clazz : clients) {
basePackages.add(ClassUtils.getPackageName(clazz));
clientClasses.add(clazz.getCanonicalName());
}
AbstractClassTestingTypeFilter filter = new AbstractClassTestingTypeFilter() {
@Override
protected boolean match(ClassMetadata metadata) {
String cleaned = metadata.getClassName().replaceAll("\\$", ".");
return clientClasses.contains(cleaned);
}
};
scanner.addIncludeFilter(
new AllTypeFilter(Arrays.asList(filter, annotationTypeFilter)));
}
for (String basePackage : basePackages) {
Set<BeanDefinition> candidateComponents = scanner
.findCandidateComponents(basePackage);
for (BeanDefinition candidateComponent : candidateComponents) {
if (candidateComponent instanceof AnnotatedBeanDefinition) {
// verify annotated class is an interface
AnnotatedBeanDefinition beanDefinition = (AnnotatedBeanDefinition) candidateComponent;
AnnotationMetadata annotationMetadata = beanDefinition.getMetadata();
Assert.isTrue(annotationMetadata.isInterface(),
"@FeignClient can only be specified on an interface");
Map<String, Object> attributes = annotationMetadata
.getAnnotationAttributes(
FeignClient.class.getCanonicalName());
String name = getClientName(attributes);
registerClientConfiguration(registry, name,
attributes.get("configuration"));
registerFeignClient(registry, annotationMetadata, attributes);
}
}
}
}
private void registerFeignClient(BeanDefinitionRegistry registry,
AnnotationMetadata annotationMetadata, Map<String, Object> attributes) {
String className = annotationMetadata.getClassName();
BeanDefinitionBuilder definition = BeanDefinitionBuilder
.genericBeanDefinition(FeignClientFactoryBean.class);
validate(attributes);
definition.addPropertyValue("url", getUrl(attributes));
definition.addPropertyValue("path", getPath(attributes));
String name = getName(attributes);
definition.addPropertyValue("name", name);
String contextId = getContextId(attributes);
definition.addPropertyValue("contextId", contextId);
definition.addPropertyValue("type", className);
definition.addPropertyValue("decode404", attributes.get("decode404"));
definition.addPropertyValue("fallback", attributes.get("fallback"));
definition.addPropertyValue("fallbackFactory", attributes.get("fallbackFactory"));
definition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE);
String alias = contextId + "FeignClient";
AbstractBeanDefinition beanDefinition = definition.getBeanDefinition();
boolean primary = (Boolean) attributes.get("primary"); // has a default, won't be
// null
beanDefinition.setPrimary(primary);
String qualifier = getQualifier(attributes);
if (StringUtils.hasText(qualifier)) {
alias = qualifier;
}
BeanDefinitionHolder holder = new BeanDefinitionHolder(beanDefinition, className,
new String[] { alias });
BeanDefinitionReaderUtils.registerBeanDefinition(holder, registry);
}
// 其他省略代码...
}
在FeignAutoConfiguration中,定义了Bean HystrixTargeter,该类设置了接口与fallbackFactory的关系并最终在HystrixInvocationHandler类中完成绑定,关键就是在这里了,这个一个JDK的动态代理类。
final class HystrixInvocationHandler implements InvocationHandler {
// 其他省略代码...
@Override
public Object invoke(final Object proxy, final Method method, final Object[] args)
throws Throwable {
// early exit if the invoked method is from java.lang.Object
// code is the same as ReflectiveFeign.FeignInvocationHandler
if ("equals".equals(method.getName())) {
try {
Object otherHandler =
args.length > 0 && args[0] != null ? Proxy.getInvocationHandler(args[0]) : null;
return equals(otherHandler);
} catch (IllegalArgumentException e) {
return false;
}
} else if ("hashCode".equals(method.getName())) {
return hashCode();
} else if ("toString".equals(method.getName())) {
return toString();
}
HystrixCommand<Object> hystrixCommand =
new HystrixCommand<Object>(setterMethodMap.get(method)) {
@Override
protected Object run() throws Exception {
try {
return HystrixInvocationHandler.this.dispatch.get(method).invoke(args);
} catch (Exception e) {
throw e;
} catch (Throwable t) {
throw (Error) t;
}
}
@Override
protected Object getFallback() {
if (fallbackFactory == null) {
return super.getFallback();
}
try {
Object fallback = ((ExtFallbackFactory)fallbackFactory).create(method, getExecutionException());
Object result = fallbackMethodMap.get(method).invoke(fallback, args);
// 其他省略代码...
}
};
// 其他省略代码...
}
}
可以看到如果指定了fallback,优先fallback回调,可以看到下面代码调用fallbackFactory.create进行降级回调。
Object fallback = ((ExtFallbackFactory)fallbackFactory).create(method, getExecutionException());
Object result = fallbackMethodMap.get(method).invoke(fallback, args);
FallbackFactory仅仅提供了一个T create(Throwable cause);
方法,仅仅通过cause无法解析出更好的信息出来,另外FallbackFactory的泛型必须和接口匹配,否则会报错
public abstract class ExtFallbackFactory<T> implements FallbackFactory<T> {
@Override
public T create(Throwable cause) {
// donothing
return null;
}
// 需要method获取对应的接口class
public abstract T create(Method method, Throwable cause);
}
复制框架原有的feign.hystrix.HystrixInvocationHandler源码,Copy放到我们应用服务的src/main目录下对应的目录下(feign.hystrix
),达到覆盖原有代码的目的,具体改动如下:
//注释掉原有的
//Object fallback = ((ExtFallbackFactory)fallbackFactory).create(getExecutionException());
//这里改成我们自己的
Object fallback = ((ExtFallbackFactory)fallbackFactory).create(method, getExecutionException());
@Slf4j
@Component
public class FeignFallbackFactory<T> extends ExtFallbackFactory<T> {
private static final ThrowableAnalyzer THROWABLE_ANALYZER = new DefaultThrowableAnalyzer();
@Override
public T create(Method method, Throwable cause) {
return createFallbackService(cause, method.getDeclaringClass());
}
private T createFallbackService(Throwable ex, Class<?> targetClass) {
Throwable[] causeChain = THROWABLE_ANALYZER.determineCauseChain(ex);
RetryableException ase1 = (RetryableException) THROWABLE_ANALYZER.getFirstThrowableOfType(RetryableException.class, causeChain);
log.error("服务出错了", ex);
if (ase1 != null) {
return toResponse("服务[{}]接口调用超时!", ase1.request());
}
FeignException ase2 = (FeignException) THROWABLE_ANALYZER.getFirstThrowableOfType(FeignException.class, causeChain);
if (ase2 != null) {
return toResponse("服务[{}]接口调用出错了!", ase2.request());
}
// 创建一个JDK代理类
return ProxyUtil.newProxyInstance((proxy, method, args) -> XCloudResponse.failed(ex.getMessage()), targetClass);
}
private T toResponse(String respMsg, Request request) {
Target<?> target = request.requestTemplate().feignTarget();
Class<?> targetClazz = target.type();
String serviceName = target.name();
return ProxyUtil.newProxyInstance((proxy, method, args) -> XCloudResponse.failed(StrUtil.format(respMsg, serviceName)), targetClazz);
}
}
在Feign接口上添加注解,指定FallbackFactory,如下:
@FeignClient(value = "${serviceName}", fallbackFactory = FeignFallbackFactory.class)
类ProxyUtil是hutool工具包的,用于创建动态代理类
类XCloudResponse是自定义封装的,如下
@Getter
@ToString
public class XCloudResponse<T> implements Serializable {
/**
* 状态码
*/
private int code;
/**
* 响应消息
*/
private String msg;
/**
* 消息负载
*/
private T payload;
public XCloudResponse() {
}
public XCloudResponse(int code, String message, T payload) {
this.code = code;
this.msg = message;
this.payload = payload;
}
public static <T> XCloudResponse<T> failed(String message) {
return failed(BAD_REQUEST, message);
}
// 此处省略代码....
}