
Spring Cloud Feign 之自定义配置
环境信息: java 1.8、Spring boot 1.5.10.RELEASE、spring cloud-Edgware.SR3、maven 3.3+
使用Feign默认配置可能不能满足需求,这时就需要我们实现自己的Feign配置,如下几种配置
application.properties(.yml)全局和局部(针对单个Feign接口),包含以下配置
spring java config全局配置和局部(针对单个Feign接口)
application.properties(.yml)配置文件和java config的优先级
下面代码就是处理配置使之生效,FeignClientFactoryBean#configureFeign :
protected void configureFeign(FeignContext context, Feign.Builder builder) {
//配置文件,以feign.client开头
FeignClientProperties properties = applicationContext.getBean(FeignClientProperties.class);
if (properties != null) {
if (properties.isDefaultToProperties()) {
//使用java config 配置
configureUsingConfiguration(context, builder);
//
configureUsingProperties(properties.getConfig().get(properties.getDefaultConfig()), builder);
configureUsingProperties(properties.getConfig().get(this.name), builder);
} else {
configureUsingProperties(properties.getConfig().get(properties.getDefaultConfig()), builder);
configureUsingProperties(properties.getConfig().get(this.name), builder);
configureUsingConfiguration(context, builder);
}
} else {
configureUsingConfiguration(context, builder);
}
}
所有配置都是单个属性覆盖,如果对 Spring boot配置优先级有所了解
第一种:配置文件无配置
使用 java config 配置,优先级有低到高进行单个配置覆盖
1、FeignClientsConfiguration Spring Cloud Feign 全局默认配置。
2、@EnableFeignClients#defaultConfiguration 自定义全局默认配置。
3、FeignClient#configuration 单个Feign接口局部配置。
第二种:feign.client.default-to-properties=true(默认true)
java config 和application.properties(.yml)配置,优先级有低到高进行单个配置覆盖
1、FeignClientsConfiguration Spring Cloud Feign 全局默认配置。
2、@EnableFeignClients#defaultConfiguration 自定义全局默认配置。
3、FeignClient#configuration 单个Feign接口局部配置。
4、application.properties(.yml)配置文件全局默认配置,配置属性feign.client.default-config指定默认值(defult),如何使用,在application.properties(.yml)配置文件应用小节讲解
5、application.properties(.yml)配置文件局部配置,指定@FeignClient#name局部配置。
第三种:feign.client.default-to-properties=false(默认true)
java config 和application.properties(.yml)配置,优先级有低到高进行单个配置覆盖
1、application.properties(.yml)配置文件全局默认配置,配置属性feign.client.default-config指定默认值(defult),如何使用,在application.properties(.yml)配置文件应用小节讲解
2、application.properties(.yml)配置文件局部配置,指定@FeignClient#name局部配置。
3、FeignClientsConfiguration Spring Cloud Feign 全局默认配置。
4、@EnableFeignClients#defaultConfiguration 自定义全局默认配置。
5、FeignClient#configuration 单个Feign接口局部配置。
application.properties(.yml)配置文件应用
支持以下配置项:
private Logger.Level loggerLevel;//日志级别
private Integer connectTimeout;//连接超时时间 java.net.HttpURLConnection#getConnectTimeout(),如果使用Hystrix,该配置无效
private Integer readTimeout;//读取超时时间 java.net.HttpURLConnection#getReadTimeout(),如果使用Hystrix,该配置无效
private Class<Retryer> retryer;//重试接口实现类,默认实现 feign.Retryer.Default
private Class<ErrorDecoder> errorDecoder;//错误编码
private List<Class<RequestInterceptor>> requestInterceptors;//请求拦截器
private Boolean decode404;//是否开启404编码
使用全局默认配置名称:defalut
feign.client.config.defalut.error-decoder=com.example.feign.MyErrorDecoder
feign.client.config.defalut.logger-level=full
...
修改全局默认配置名称为:my-config
feign.client.default-config=my-config
feign.client.config.my-config.error-decoder=com.example.feign.MyErrorDecoder
feign.client.config.my-config.logger-level=full
局部配置,@FeignClient#name=user
feign.client.config.user.error-decoder=com.example.feign.MyErrorDecoder
feign.client.config.user.logger-level=full
java config配置应用
可配置的接口或类,通过@EnableFeignClients#defaultConfiguration全局默认和@FeignClient#configuration局部Feign接口配置:
全局:
@EnableFeignClients(
defaultConfiguration = FeignClientsConfig.class
)
@SpringBootApplication
public class FeignApplication {
public static void main(String[] args) {
SpringApplication.run(FeignApplication.class, args);
}
}
局部:
@FeignClient(name = "user", url = "${user.url}",
configuration = UserFeignClientConfig.class
)
public interface UserFeign {
@PostMapping
Completable save(User user);
@GetMapping("/{id}")
Single<User> getUserByIDSingle(@PathVariable("id") String id);
@GetMapping("/{id}")
Observable<User> getUserByID(@PathVariable("id") String id);
@GetMapping
HystrixCommand<List<User>> findAll();
}
具体配置项如下,如何配置可以参考FeignClientsConfiguration类:
Logger.Level:日志级别
Retryer:重试机制
ErrorDecoder:错误解码器
Request.Options:
参考application.properties(.yml)配置文件应用
private final int connectTimeoutMillis;// connectTimeout配置项
private final int readTimeoutMillis;// readTimeout配置项
RequestInterceptor:请求拦截器
Contract:处理Feign接口注解,Spring Cloud Feign 使用SpringMvcContract 实现,处理Spring mvc 注解,也就是我们为什么可以用Spring mvc 注解的原因。
Client:Http客户端接口,默认是Client.Default,但是我们是不使用它的默认实现,Spring Cloud Feign为我们提供了okhttp3和ApacheHttpClient两种实现方式,只需使用maven引入以下两个中的一个依赖即可,版本自由选择。
<!--feign 集成httpclient-->
<dependency>
<groupId>com.netflix.feign</groupId>
<artifactId>feign-httpclient</artifactId>
<version>8.3.0</version>
</dependency>
<!--feign集成okhttp-->
<dependency>
<groupId>com.netflix.feign</groupId>
<artifactId>feign-okhttp</artifactId>
<version>8.18.0</version>
</dependency>
Encoder:编码器,将一个对象转换成http请求体中, Spring Cloud Feign 使用 SpringEncoder
Decoder:解码器, 将一个http响应转换成一个对象,Spring Cloud Feign 使用 ResponseEntityDecoder
FeignLoggerFactory:日志工厂参考Spring Cloud Feign 之日志自定义扩展
Feign.Builder:Feign接口构建类,覆盖默认Feign.Builder,比如:HystrixFeign.Builder
FeignContext管理了所有的java config 配置
/**
* A factory that creates instances of feign classes. It creates a Spring
* ApplicationContext per client name, and extracts the beans that it needs from there.
*
* @author Spencer Gibb
* @author Dave Syer
*/
public class FeignContext extends NamedContextFactory<FeignClientSpecification> {
public FeignContext() {
super(FeignClientsConfiguration.class, "feign", "feign.client.name");
}
}
自定义类型转换注册FeignFormatterRegistrar
Spring提供了一个接口ConversionService可以将任意类型转换成指定类型,如果String->Integer
当然这些转换器需要实现一些Spring提供的类型转换接口,如:Converter(转换器),ConverterFactory(转换工厂),Formatter(格式化)等等。
我们来添加一个简单的转换器,将String->Integer
package com.example.feign;
import org.springframework.cloud.netflix.feign.FeignFormatterRegistrar;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.converter.Converter;
import org.springframework.format.FormatterRegistry;
/**
* Feign 格式转换器
* @author: sunshaoping
* @date: Create by in 上午10:51 2018/9/15
* @see ConversionService
*/
@Configuration
public class FeignFormatterRegistrarConfig implements FeignFormatterRegistrar {
@Override
public void registerFormatters(FormatterRegistry registry) {
//字符串转换成Integer
registry.addConverter(String.class, Integer.class, Integer::valueOf);//lambda表达式
}
}
更多请参考Spring 官方文档
自定义方法参数注解 AnnotatedParameterProcessor
Demo中的UserFeign#getUserByID方法就使用了方法参数注解@PathVariable,这个注解就是通过实现AnnotatedParameterProcessor接口实现的
public class PathVariableParameterProcessor implements AnnotatedParameterProcessor {
private static final Class<PathVariable> ANNOTATION = PathVariable.class;
@Override
public Class<? extends Annotation> getAnnotationType() {
return ANNOTATION;
}
@Override
public boolean processArgument(AnnotatedParameterContext context, Annotation annotation, Method method) {
String name = ANNOTATION.cast(annotation).value();
checkState(emptyToNull(name) != null,
"PathVariable annotation was empty on param %s.", context.getParameterIndex());
context.setParameterName(name);
MethodMetadata data = context.getMethodMetadata();
String varName = '{' + name + '}';
if (!data.template().url().contains(varName)
&& !searchMapValues(data.template().queries(), varName)
&& !searchMapValues(data.template().headers(), varName)) {
data.formParams().add(name);
}
return true;
}
private <K, V> boolean searchMapValues(Map<K, Collection<V>> map, V search) {
Collection<Collection<V>> values = map.values();
if (values == null) {
return false;
}
for (Collection<V> entry : values) {
if (entry.contains(search)) {
return true;
}
}
return false;
}
}
通过上面源码我们也可以实现自己的方法参数注解,这里就不做演示了,说明下注意事项和注册方式。
注册方式
很简单就行普通的java 对象注册到Spring容器一样将实现类使用Spring相关注解 @Configuration、@Bean等等
@Bean
AnnotatedParameterProcessor annotatedParameterProcessor(){
return new PathVariableParameterProcessor();
}
注意事项
如果自定义实现AnnotatedParameterProcessor接口,Spring Cloud Feign 默认方法参数注解将失效,通过部分源码可以知:
public class SpringMvcContract extends Contract.BaseContract
implements ResourceLoaderAware {
//spring mvc 注解处理类的构造器
public SpringMvcContract(
List<AnnotatedParameterProcessor> annotatedParameterProcessors,
ConversionService conversionService) {
Assert.notNull(annotatedParameterProcessors,
"Parameter processors can not be null.");
Assert.notNull(conversionService, "ConversionService can not be null.");
List<AnnotatedParameterProcessor> processors;
if (!annotatedParameterProcessors.isEmpty()) {
processors = new ArrayList<>(annotatedParameterProcessors);
}
else {
//当前annotatedParameterProcessors 为空时使用默认
processors = getDefaultAnnotatedArgumentsProcessors();
}
this.annotatedArgumentProcessors = toAnnotatedArgumentProcessorMap(processors);
this.conversionService = conversionService;
this.expander = new ConvertingExpander(conversionService);
}
...
private List<AnnotatedParameterProcessor> getDefaultAnnotatedArgumentsProcessors() {
List<AnnotatedParameterProcessor> annotatedArgumentResolvers = new ArrayList<>();
annotatedArgumentResolvers.add(new PathVariableParameterProcessor());
annotatedArgumentResolvers.add(new RequestParamParameterProcessor());
annotatedArgumentResolvers.add(new RequestHeaderParameterProcessor());
return annotatedArgumentResolvers;
}
}
@RequestMapping也被SpringMVC加载的问题解决
Feign接口类有@RequestMapping注解SpringMVC会加载到HandlerMapping中,如果存在相同ual路径还会报错
关于这个问题解决方法可以参考 @FeignClient中的@RequestMapping也被SpringMVC加载的问题解决
总结
本章节介绍了如何进行Feign自定义配置包括全局和局部、application.properties配置文件和java config配置,及其优先级配置。
样例地址 spring-cloud-feign 分支 Spring-Cloud-Feign-之自定义配置
写在最后
Spring Cloud Feign 系列持续更新中。。。。。欢迎关注
如发现哪些知识点有误或是没有看懂,请在评论区指出,博主及时改正。
欢迎转载请注明出处。

本文详细探讨了Spring Cloud Feign的自定义配置,包括application.properties(.yml)配置文件和Java Config的优先级。讲解了三种配置情况:无配置、default-to-properties=true和default-to-properties=false时的配置覆盖规则。还介绍了全局和局部配置,以及如何注册自定义类型转换FeignFormatterRegistrar和方法参数注解AnnotatedParameterProcessor。同时解决了@RequestMapping被SpringMVC加载的问题,并给出了自定义配置的总结和样例代码链接。
167万+

被折叠的 条评论
为什么被折叠?



