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 系列持續更新中。。。。。歡迎關注
如發現哪些知識點有誤或是沒有看懂,請在評論區指出,博主及時改正。
歡迎轉載請註明出處。