概要
接上一篇《Spring Cloud 学习笔记06----断路器(Hystrix)(Finchley版本)》,今天我们来学习另外一种服务调用方式(Feign),之前我们介绍了 RestTemplate+Ribbon 消费服务的方式。
Feign简介
Feign 是一个声明式的伪Http客户端,它使得写Http 客户端变得更简单,使用Feign,只需要创建一个接口并注解。它具有可插拔的注解特性,可使用Feign注解和JAX-RS注解,Feign 也支持可插拔的编码器和解码器,Spring Cloud 扩展了对Spring MVC的注解支持,在Spring Web 中同样使用HttpMessageConverters
。Feign 默认集成了Ribbon, 并和Eureka 结合,默认实现了负载均衡的效果。
简单来说:
- Feign 采用的是基于接口的注解
- Feign 整合了Ribbon, 具有负载均衡的能力
- 整合了Hystrix,具有熔断能力。
快速入门
首先,沿用前面的服务注册中心(eureka-server)以及服务提供者(order-provider)。然后新建一个SpringBoot 项目,命名为service-feign。添加依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--必须添加spring-boot-starter-web,否则注册失败-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
然后,在application.yml 加上如下配置,指定端口为8765,服务名为service-feign:
spring:
application:
name: service-feign
eureka:
client:
service-url:
# 用于指定注册中心的地址
defaultZone: http://localhost:1111/eureka/
server:
port: 8765
接着,我们在ServiceFeignApplication 中添加@EnableFeignClients
以激活Feign。添加@EnableEurekaClient
以开启负载均衡,使其可以注册到Eureka 中。
。。。。。。。。。。。。。。。。。
版权原因,完整文章,请参考如下:Spring Cloud 学习笔记08----服务消费者(Feign)(Finchley版本)