文章内容参考springcloud官方文档Spring Cloud OpenFeign,版本为3.0.4
Spring Cloud OpenFeign项目设计的初衷是将OpenFeign与Springboot项目进行整合,整合后使用springboot自动装配将其托管到spring容器中
Feign设计为声明式web服务客户端简化了web服务间的请求,在没有使用过Feign前请求http接口需要大量的代码书写与各种配置设置,Feign通过接口+注解的方式进行声明,支持的注解:Feign annotations & JAX-RS annotations,Feign支持可插拔的编码器与解码器例如 Java bean -> Json & Json -> Java Bean,为了兼容Spring MVC模块中注解Spring Web 默认使用HttpMessageConverters,Spring Cloud LoadBalancer*为Feign提供了负载均衡功能
在springcloud 项目pom中引入相应的starter即可
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
引入后在项目启动类上开启 @EnableFeignClients即可
@SpringBootApplication
@EnableFeignClients
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
通过接口+注解方式声明如下所示
@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);
}
@EnableFeignClients可以扫描指定包下所有接口例如:@EnableFeignClients(basePackages =
“com.example.clients”)
Springcloud 根据 @FeignClient& FeignClientsConfiguration在容器中创建Feign,FeignClientsConfiguration包含feign.Decoder,feign.Encoder,feign.Contract.Feign针对每个FeignClient提供了自定义配置
@FeignClient(name = "stores", configuration = FooConfiguration.class)
public interface StoreClient {
//..
}
在上例中FeignClient的创建将会通过FeignClientsConfiguration和FooConfiguration,后者配置将会覆盖前者
FooConfiguration不需要使用@Configration注解,如果加了该注解需要在扫描包的注解中将此类排除不然此类就会成为默认配置
Spring Cloud OpenFeign提供如下bean作为Feign默认配置
Decoder feignDecoder: ResponseEntityDecoder (which wraps a SpringDecoder)
Encoder feignEncoder: SpringEncoder
Logger feignLogger: Slf4jLogger
MicrometerCapability micrometerCapability: If feign-micrometer is on the classpath and MeterRegistry is available
Contract feignContract: SpringMvcContract
Feign.Builder feignBuilder: FeignCircuitBreaker.Builder
Client feignClient: If Spring Cloud LoadBalancer is on the classpath, FeignBlockingLoadBalancerClient is used. If none of them is on the classpath, the default feign client is used.
本文只截取官方文档一部分进行介绍,更多内容请参考官方文档