背景
在spring应用中,原始的openfeign生成的代理对象是没有直接在spring容器中注入的,要使用openfeign的原生使用方式如下所示。
这种方式,对一个有追求的程序员来说很不优雅,本文来解决将feign整合到spring中的问题,实现feign的优雅使用。
解决上一个问题,之后我们还问自己一个问题,feign的作用是http的rpc调用,但是http的调用如何优雅的实现服务熔断和降级呢?很明显用hystrix,这里又有问题了,hystrix和feign分别生成的动态代理对象是不兼容的,feign是需要手动创建代理对象,而hystrix可以通过spring创建或者通过command api来创建,如何将 feign和hystrix一起整合到spring中呢?
带着这两个问题我们继续。
feign
首先feign的介绍可以参考上一篇博文:添feign的基本使用和源码解析,讲解了feign的使用和工作流程和源码解析。
回顾一下feign使用,Feign.builder() .target()会创建GitHub类的动态代理对象GitHubProxy即github实例
public class MyApp {
public static void main(String[] args) {
GitHub github = Feign.builder()
.decoder(new GsonDecoder())
.target(GitHub.class, "https://api.github.com");
/**
*@Param注解的参数会按照名字填充{owner}{repo}
HousonCao/Hystrix
*/
github.contributors("HousonCao", "Hystrix");
}
}
hystrix
hystric使用和原理介绍参考:
https://mp.csdn.net/console/editor/html/111477766
spring整合feign和hystrix
本文重点阐述如何将第三方框架集成到spring,以spring集成hystrix-feign扩展为例展示spring集成三方框架的流程。
首先说明一下需求:
feign在springboot中是可以和feign和hystrix一起使用的,但是在spring中需要自己集成到spring,我们基于
和他的扩展
实现spring整合feign和hystrix,达到声明式的http RPC调用,同时支持RxJava响应式编程的目标。我们思考一下:mybatis是如何实现和spring集成的呢,我们要做的和mybatis很类似,甚至可以照葫芦画瓢。
public void setHttpClient(OkHttpClientService httpClient) {
this.httpClient = httpClient;
}
public Class getFallback() {
return fallback;
}
public void setFallback(Class fallback) {
this.fallback = fallback;
}
public FeignRegistry getFeignRegistry() {
return feignRegistry;
}
public void setFeignRegistry(FeignRegistry feignRegistry) {
this.feignRegistry = feignRegistry;
}
/**
* {@inheritDoc}
*/
@Override
public T getObject() throws Exception {
if (feignRegistry.getMapper(hystrixFeignInterface) == null) {
notNull(this.hystrixFeignInterface, "Property 'mapperInterface' is required");
// create feign hystrix client instance
LOGGER.info("创建feign客户端参数:Uri:{}",uri);
Object feignClient = TraceHystrixFeign.builder()
.setterFactory(setterFactory)
.encoder(encoder)
.decoder(decoder)
.logger(logger)
.logLevel(Level.FULL)
.retryer(new NoRetryer())
.client(new OkHttpClient(httpClient.getmOkHttpClient()))
.options(new Options(httpClient.getConnectTimeout(), httpClient.getReadTimeout()))
.target(hystrixFeignInterface, uri, new FallbackFactory() {
@Override
public Object create(Throwable cause) {
try {
return BeanUtils.instantiateClass(fallback.getConstructor(Throwable.class), cause);
} catch (NoSuchMethodException e) {
LOGGER.warn("创建fallback失败",e);
throw new RuntimeException(e);
}
}
});
// add feign hystrix interface target instance to set
feignRegistry.addMapper(hystrixFeignInterface, feignClient);
}
// get from set
return (T) feignRegistry.getMapper(hystrixFeignInterface);
}
/**
* {@inheritDoc}
*/
@Override
public Class<T> getObjectType() {
return this.hystrixFeignInterface;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isSingleton() {
return true;
}
public Class<T> getHystrixFeignInterface() {
return hystrixFeignInterface;
}
public void setHystrixFeignInterface(Class<T> hystrixFeignInterface) {
this.hystrixFeignInterface = hystrixFeignInterface;
}
}
bean定义完了需要定义注解,让客户端能配置factorybean的属性。这里直接将@hystrixCommand的部分属性搬过来。
```java
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
public @interface HystrixFeign {
String feignRegistry() default "feignRegistry";
Class fallbackRef() ;
/**
* feign的请求body编码器
* @return
*/
String encoderRef() default "";
/**
* feign 响应解码器
* @return
*/
String decoderRef() default "";
String httpClient() default "";
String uri() default "";
/**
* The command group key is used for grouping together commands such as for reporting,
* alerting, dashboards or team/library ownership.
* <p/>
* default => the runtime class name of annotated method
*
* @return group key
*/
String groupKey() default "";
/**
* Hystrix command key.
* <p/>
* default => the name of annotated method. for example:
* <code>
* ...
* @HystrixCommand
* public User getUserById(...)
* ...
* the command name will be: 'getUserById'
* </code>
*
* @return command key
*/
String commandKey() default "";
/**
* The thread-pool key is used to represent a
* HystrixThreadPool for monitoring, metrics publishing, caching and other such uses.
*
* @return thread pool key
*/
String threadPoolKey() default "";
/**
* Specifies a method to process fallback logic.
* A fallback method should be defined in the same class where is HystrixCommand.
* Also a fallback method should have same signature to a method which was invoked as hystrix command.
* for example:
* <code>
* @HystrixCommand(fallbackMethod = "getByIdFallback")
* public String getById(String id) {...}
*
* private String getByIdFallback(String id) {...}
* </code>
* Also a fallback method can be annotated with {@link HystrixCommand}
* <p/>
* default => see {@link com.netflix.hystrix.contrib.javanica.command.GenericCommand#getFallback()}
*
* @return method name
*/
String fallbackMethod() default "";
/**
* Specifies command properties.
*
* @return command properties
*/
HystrixProperty[] commandProperties() default {};
/**
* Specifies thread pool properties.
*
* @return thread pool properties
*/
HystrixProperty[] threadPoolProperties() default {};
/**
* Defines exceptions which should be ignored.
* Optionally these can be wrapped in HystrixRuntimeException if raiseHystrixExceptions contains RUNTIME_EXCEPTION.
*
* @return exceptions to ignore
*/
Class<? extends Throwable>[] ignoreExceptions() default {};
/**
* Specifies the mode that should be used to execute hystrix observable command.
* For more information see {@link ObservableExecutionMode}.
*
* @return observable execution mode
*/
ObservableExecutionMode observableExecutionMode() default ObservableExecutionMode.EAGER;
/**
* When includes RUNTIME_EXCEPTION, any exceptions that are not ignored are wrapped in HystrixRuntimeException.
*
* @return exceptions to wrap
*/
HystrixException[] raiseHystrixExceptions() default {};
/**
* Specifies default fallback method for the command. If both {@link #fallbackMethod} and {@link #defaultFallback}
* methods are specified then specific one is used.
* note: default fallback method cannot have parameters, return type should be compatible with command return type.
*
* @return the name of default fallback method
*/
String defaultFallback() default "";
}
定义完属性,我们继续
bean扫描
-
继承Spring提供的ClassPathBeanDefinitionScanner 进行beandefinition的扫描,实现doScan方法,生成beandefinition,返回beandefinition集合进行注册。类似spring的@component注解需要有个扫描的过程。
public class ClassPathHystrixFeignScanner extends ClassPathBeanDefinitionScanner { public static final Logger LOGGER = LoggerFactory.getLogger(ClassPathHystrixFeignScanner.class); private Class<? extends Annotation> annotationClass; private HystrixFeignFactoryBean mapperFactoryBean = new HystrixFeignFactoryBean(); public ClassPathHystrixFeignScanner(BeanDefinitionRegistry registry) { super(registry, false); } public void setAnnotationClass(Class<? extends Annotation> annotationClass) { this.annotationClass = annotationClass; } public void setMapperFactoryBean(HystrixFeignFactoryBean mapperFactoryBean) { this.mapperFactoryBean = (mapperFactoryBean != null ? mapperFactoryBean : new HystrixFeignFactoryBean()); } /** * Configures parent scanner to search for the right interfaces. It can search for all interfaces or just for those * that extends a markerInterface or/and those annotated with the annotationClass */ public void registerFilters() { boolean acceptAllInterfaces = true; // if specified, use the given annotation and / or marker interface if (this.annotationClass != null) { addIncludeFilter(new AnnotationTypeFilter(this.annotationClass)); acceptAllInterfaces = false; } // override AssignableTypeFilter to ignore matches on the actual marker interface if (acceptAllInterfaces) { // default include filter that accepts all classes addIncludeFilter(new TypeFilter() { @Override public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException { return true; } }); } // exclude package-info.java addExcludeFilter(new TypeFilter() { @Override public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException { String className = metadataReader.getClassMetadata().getClassName(); return className.endsWith("package-info"); } }); } /** * Calls the parent search that will search and register all the candidates. Then the registered objects are post * processed to set them as MapperFactoryBeans */ @Override public Set<BeanDefinitionHolder> doScan(String... basePackages) { Set<BeanDefinitionHolder> beanDefinitions = super.doScan(basePackages); if (beanDefinitions.isEmpty()) { logger.warn("No hystrix feign was found in '" + Arrays.toString(basePackages) + "' package. Please check your configuration."); } else { processBeanDefinitions(beanDefinitions); } return beanDefinitions; } private void processBeanDefinitions(Set<BeanDefinitionHolder> beanDefinitions) { GenericBeanDefinition definition; for (BeanDefinitionHolder holder : beanDefinitions) { definition = (GenericBeanDefinition) holder.getBeanDefinition(); definition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_NAME); if (logger.isDebugEnabled()) { logger.debug("Creating HystrixFeignFactoryBean with name '" + holder.getBeanName() + "' and '" + definition.getBeanClassName() + "' HystrixFeign Interface"); } // the hystrixFeign interface is the original class of the bean // but, the actual class of the bean is HystrixFeignFactoryBean definition.getPropertyValues().add("hystrixFeignInterface", definition.getBeanClassName()); //TODO 解析interface的方法注解获取hystrix配置 String realBeanClassName = definition.getBeanClassName(); Class<?> realBeadClass = null; try { realBeadClass = Class.forName(realBeanClassName); } catch (ClassNotFoundException e) { LOGGER.warn("扫描hystrix feign失败",e); } HystrixFeign annotation = realBeadClass.getAnnotation(HystrixFeign.class); if (annotation == null) { LOGGER.warn("HystrixFeign 注解不存在:{}", realBeadClass); continue; } GenericSetterBuilder.Builder setterBuilder = GenericSetterBuilder.builder() .groupKey(annotation.groupKey()) .threadPoolKey(annotation.threadPoolKey()) .commandKey(annotation.commandKey()) .commandProperties(Arrays.asList(annotation.commandProperties())) .threadPoolProperties(Arrays.asList(annotation.threadPoolProperties())); GenericSetterBuilder build = setterBuilder.build(); Setter setter = build.build(); definition.getPropertyValues().add("setterFactory", new HystrixFeignSetterFactory(setter)); String uri = annotation.uri(); String uriProperty = getEnvironment().resolveRequiredPlaceholders(uri); int indexOfSep= uri.indexOf(":"); if (indexOfSep!=-1){ String urlKey = uri.substring(2, indexOfSep); String remoteUri= ConfigManager.getString(urlKey); if(StringUtils.isNotEmpty(remoteUri)){ definition.getPropertyValues().add("uri", remoteUri); }else{ definition.getPropertyValues().add("uri", uriProperty); } } definition.getPropertyValues().add("httpClient", new RuntimeBeanReference(annotation.httpClient())); if (StringUtils.isNotEmpty(annotation.decoderRef())) { definition.getPropertyValues().add("decoder", new RuntimeBeanReference(annotation.decoderRef())); } definition.getPropertyValues().add("fallback", annotation.fallbackRef()); definition.getPropertyValues().add("feignRegistry", new RuntimeBeanReference(annotation.feignRegistry())); if (StringUtils.isNotEmpty(annotation.encoderRef())) { definition.getPropertyValues().add("encoder", new RuntimeBeanReference(annotation.encoderRef())); } if (StringUtils.isNotEmpty(annotation.decoderRef())) { definition.getPropertyValues().add("decoder", new RuntimeBeanReference(annotation.decoderRef())); } definition.setBeanClass(this.mapperFactoryBean.getClass()); // definition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE); } } /** * {@inheritDoc} */ @Override protected boolean isCandidateComponent(AnnotatedBeanDefinition beanDefinition) { return beanDefinition.getMetadata().isInterface() && beanDefinition.getMetadata().isIndependent(); } /** * {@inheritDoc} */ @Override protected boolean checkCandidate(String beanName, BeanDefinition beanDefinition) { if (super.checkCandidate(beanName, beanDefinition)) { return true; } else { logger.warn("Skipping HystrixFeignFactoryBean with name '" + beanName + "' and '" + beanDefinition.getBeanClassName() + "' mapperInterface" + ". Bean already defined with the same name!"); return false; } } }
beandefinition注册
-
首先需要将要生成的实例的beandefinition注册到spring的beandefinition容器BeanDefinitionRegistry,如何实现呢。
-
实现方式有两种:
-
- 继承ImportBeanDefinitionRegistrar在配置类上使用@Import(HystrixFeignScannerRegistrar.class)即可在启动时加载Registrar类实例,在registerBeanDefinitions方法中将scanner扫描的beandefinitions注册到registry
- 实现BeanDefinitionRegistryPostProcessor,spring启动时调用refresh方法会调用postProcessBeanDefinitionRegistry执行注册beandefinition的代码,在这里执行ClassPathBeanDefinitionScanner的扫描逻辑,将生成的beandefinition进行注册。
-
我们选择第一种实现:源码如下:
public class HystrixFeignScannerRegistrar implements ImportBeanDefinitionRegistrar, ResourceLoaderAware {
private ResourceLoader resourceLoader;
/**
* {@inheritDoc}
*/
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
AnnotationAttributes annoAttrs = AnnotationAttributes.fromMap(importingClassMetadata.getAnnotationAttributes(
HystrixFeignScan.class.getName()));
ClassPathHystrixFeignScanner scanner = new ClassPathHystrixFeignScanner(registry);
// this check is needed in Spring 3.1
if (resourceLoader != null) {
scanner.setResourceLoader(resourceLoader);
}
Class<? extends Annotation> annotationClass = annoAttrs.getClass("annotationClass");
if (!Annotation.class.equals(annotationClass)) {
scanner.setAnnotationClass(annotationClass);
}
Class<? extends HystrixFeignFactoryBean> mapperFactoryBeanClass = annoAttrs.getClass("factoryBean");
if (!HystrixFeignFactoryBean.class.equals(mapperFactoryBeanClass)) {
scanner.setMapperFactoryBean(BeanUtils.instantiateClass(mapperFactoryBeanClass));
}
List<String> basePackages = new ArrayList<String>();
for (String pkg : annoAttrs.getStringArray("value")) {
if (StringUtils.hasText(pkg)) {
basePackages.add(pkg);
}
}
for (String pkg : annoAttrs.getStringArray("basePackages")) {
if (StringUtils.hasText(pkg)) {
basePackages.add(pkg);
}
}
scanner.registerFilters();
scanner.doScan(StringUtils.toStringArray(basePackages));
}
/**
* {@inheritDoc}
*/
@Override
public void setResourceLoader(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
}
}
配置启动扫描
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Import(HystrixFeignScannerRegistrar.class)
public @interface EnableHystrixFeign {
String[] value() default {};
String[] basePackages() default {};
Class<? extends Annotation> annotationClass() default Annotation.class;
Class<? extends HystrixFeignFactoryBean> factoryBean() default HystrixFeignFactoryBean.class;
}
使用举例
@HystrixFeign(commandKey = "expressApi",
threadPoolKey = "expressPool",
uri = "${test.url:http://localhost:8080/test_hystrix_feign}",
fallbackRef = ExpressApi.ExpressFallback.class,
httpClient = "okHttpClient",
commandProperties = {
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1000"),
},
threadPoolProperties = {
@HystrixProperty(name = "coreSize", value = "20"),
@HystrixProperty(name = "maximumSize", value = "20")
})
public interface ExpressApi {
@RequestLine("POST ")
@Headers({"Content-Type: application/json", "host: localhost:8080"})
String getExpressInfos(ExpressQueryParam queryParam);
@Slf4j
@AllArgsConstructor
class ExpressFallback implements ExpressApi {
Throwable t;
@Override
public String getExpressInfos(ExpressQueryParam queryParam) {
return null;
}
}
}