1、介绍
Feign是Netflix开发的声明式、模板化的HTTP客户端, Feign可以帮助我们更快捷、优雅地调用HTTP API。
在Spring Cloud中,使用Feign非常简单——创建一个接口,并在接口上添加一些注解,代码就完成了。Feign支持多种注解,例如Feign自带的注解或者JAX-RS注解等。
Spring Cloud对Feign进行了增强,使Feign支持了Spring MVC注解,并整合了Ribbon和Eureka,从而让Feign的使用更加方便。
Spring Cloud Feign是基于Netflix feign实现,整合了Spring Cloud Ribbon和Spring Cloud Hystrix,除了提供这两者的强大功能外,还提供了一种声明式的Web服务客户端定义的方式。
Spring Cloud Feign帮助我们定义和实现依赖服务接口的定义。在Spring Cloud feign的实现下,只需要创建一个接口并用注解方式配置它,即可完成服务提供方的接口绑定,简化了在使用Spring Cloud Ribbon时自行封装服务调用客户端的开发量。
Spring Cloud Feign具备可插拔的注解支持,支持Feign注解、JAX-RS注解和Spring MVC的注解。
- 远程调用 - RestTemplate
- ribbon - @LoadBalanced,配置重试参数
- hystrix
集成工具:
- 远程调用
- ribbon - 负载均衡、重试
- hystrix - 降级、熔断
2、Feign 远程调用
2.1、Feign 提供了声明式客户端,只需要定义一个接口,就可以通过接口做远程调用。具体调用代码通过动态代理添加。
// 调用商品服务的远程调用接口
// 通过注解配置3件事:调用哪个服务,调用什么路径,向这个路径提交什么参数
@FeignClient(name="item-service")
public interface ItemFeignClient {
@GetMapping("/{orderId}")
JsonResult<List<Item>> getItems(@PathVariable String orderId);
}
2.2、 添加Feign声明式客户端
(1) 添加Feign声明式客户端
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
(2)启动类加 @EnableFeignClients
@EnableFeignClients
(3)定义声明式客户端接口
eg:
- ItemFeignClient
- UserFeignClient
- OrderFeignClient
(4)添加一个测试用的控制器,使用三个声明式客户端接口调用远程服务
3、Feign 集成 Ribbon:负载均衡、重试
Feign 默认启用了Ribbon的负载均衡和重试,0配置
默认重试参数:
- MaxAutoRetries=0
- MaxAutoRetriesNextServer=1
- ReadTimeout=1000
重试参数配置
有需要则设置
# 对所有服务都有效
ribbon:
MaxAutoRetries: 1
# 对 item-service 单独配置,对其他服务无效
item-service:
ribbon:
MaxAutoRetries: 0
4、Feign 集成 Hystrix:降级、熔断、监控
默认不启用 Hystrix,Feign不推荐启用hystrix(后面再分析)
如果有特殊需求要启用hystrix,首先做基础配置
1、添加 hystrix 的完整依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
</dependency>
2、添加
@EnableCircuitBreaker
3、yml配置
feign.hystrix.enabled=true
# 启动Hystrix
# 启动Hystrix
feign:
hystrix:
enabled: true
4.1、降级
之前:加的是
@HystrixCommand(fallbackMethod=“ . . . ”)
现在:在声明式客户端接口的注解中,指定一个降级类
@FeignClient(name="item-service", fallback=降级类.class)
public interface ItemFeignClient {
....
}
降级类要作为声明式客户端接口的子类来定义
其实现类要用
@Component
来标注
4.2、熔断
熔断会自动触发:10秒20次请求,50%失败,执行了降级代码。
4.3、监控:用 actuator 暴露 hystrix.stream 监控端点
(1)添加actuator 依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
(2)暴露监控端点:m.e.w.e.i=hystrix.stream
# 暴露监控端点
management:
endpoints:
web:
exposure:
include: hystrix.stream