内容纲要
认识 Feign
Feign
- 声明式RESTWeb 服务客户端
- https://github.com/OpenFeign/feign
Spring Cloud OpenFeign
pom.xml 中引入依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
Feign的简单使用
开启Feign支持
- @EnableFeignClients
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
定义 Feign 接口
- @FeignClient
StoreClient.java
@FeignClient("stores")
public interface StoreClient {
@RequestMapping(method = RequestMethod.GET, value = "/stores")
List<Store> getStores();
@RequestMapping(method = RequestMethod.GET, value = "/stores")
Page<Store> getStores(Pageable pageable);
@RequestMapping(method = RequestMethod.POST, value = "/stores/{storeId}", consumes = "application/json")
Store update(@PathVariable("storeId") Long storeId, Store store);
@RequestMapping(method = RequestMethod.DELETE, value = "/stores/{storeId:\\d+}")
void delete(@PathVariable Long storeId);
}
简单配置
- FeignClientsConfiguration
- Encoder / Decoder / Logger / Contract / Client ...
通过配置定制Feign
application.yml
spring:
cloud:
openfeign:
client:
config:
feignName:
url: http://remote-service.com
connectTimeout: 5000
readTimeout: 5000
loggerLevel: full
errorDecoder: com.example.SimpleErrorDecoder
retryer: com.example.SimpleRetryer
defaultQueryParameters:
query: queryValue
defaultRequestHeaders:
header: headerValue
requestInterceptors:
- com.example.FooRequestInterceptor
- com.example.BarRequestInterceptor
responseInterceptor: com.example.BazResponseInterceptor
dismiss404: false
encoder: com.example.SimpleEncoder
decoder: com.example.SimpleDecoder
contract: com.example.SimpleContract
capabilities:
- com.example.FooCapability
- com.example.BarCapability
queryMapEncoder: com.example.SimpleQueryMapEncoder
micrometer.enabled: false
Feign的其他配置
配置okhttp
- feign.okhttp.enabled=true
配置httpclient(注意需要引入相关包) - feign.httpclient.enabled=true
配置压缩
- feign.compression.response.enabled=true
- feign.compression.request.enabled=true
- feign.compression.request.mime-types=text/xml,application/xml,application/json
- feign.compression.request.min-request-size=2048
server.port=0
服务器将会自动选择一个空闲的端口来运行
注意:不要在Feign接口上加@Requestmapping,避免出现一些问题(SpringMVC 会视图加载接口上定义的@RequestMapping)。
公共前缀,可以这样做:
@FeignClient(name = "xxx-service", contextId = "coffee", path="/commonPrefixHere")
如果有2个接口都注明了@FeignClient(name = "xxx-service"),contextId可以区分开,避免冲突。