Spring Cloud Feign(第六篇) 之自定義配置
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
:
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
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表示式
}
}
自定義方法引數註解 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路徑還會報錯
總結
本章節介紹瞭如何進行Feign
自定義配置包括全域性和區域性、application.properties
配置檔案和java config
配置,及其優先順序配置。
樣例地址 spring-cloud-feign 分支 Spring-Cloud-Feign-之自定義配置
寫在最後
Spring Cloud Feign 系列持續更新中。。。。。歡迎關注
如發現哪些知識點有誤或是沒有看懂,請在評論區指出,博主及時改正。
歡迎轉載請註明出處。