一、Feign
1.1 Feign 介绍
Feign 是一个声明式的Web Service客户端,它使得编写 Web Serivce 客户端变得更加简单。我们只需要使用Feign 来创建一个接口并用注解来配置它既可完成。它具备可插拔的注解支持,包括 Feign注解和 JAX-RS 注解。Feign 也支持可插拔的编码器和解码器。Spring Cloud 为 Feign 增加了对 Spring MVC 注解的支持,还整合了Ribbon 和 Eureka 来提供负载均衡的HTTP客户端实现。
1.2 FeignClient注解属性
属性名 | 默认值 | 作用 | 备注 |
---|---|---|---|
value | 空字符串 | 调用服务名称,和name属性相同 | |
serviceId | 空字符串 | 服务id,作用和name属性相同 | 已过期 |
name | 空字符串 | 调用服务名称,和value属性相同 | |
url | 空字符串 | 全路径地址或hostname,http或https可选 | |
decode404 | false | 配置响应状态码为404时是否应该抛出FeignExceptions | |
configuration | {} | 自定义当前feign client的一些配置 | 参考FeignClientsConfiguration |
fallback | void.class | 熔断机制,调用失败时,走的一些回退方法,可以用来抛出异常或给出默认返回数据。 | 底层依赖hystrix,启动类要加上@EnableHystrix |
path | 空字符串 | 自动给所有方法的requestMapping前加上前缀,类似与controller类上的requestMapping | |
primary | true |
二、Feign 简单使用
注:基于 SpringCloud之项目初始化 之上操作。
- 在 OrderService 模块中添加 Feign 依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
- 启用 Feign 注解
@EnableFeignClients
@EnableDiscoveryClient
@SpringBootApplication
public class OrderServiceApplication {
public static void main(String[] args) {
SpringApplication.run(OrderServiceApplication.class, args);
}
}
- 创建 PriceService 接口
@FeignClient(value = "PRICE-SERVICE", path = "/price")
public interface PriceService {
@RequestMapping(value = "/getPrice/{productId}", method = RequestMethod.GET)
BigDecimal getPrice(@PathVariable("productId")String productId);
}
可以看到相当于是一个和 PriceService 访问的契约。
- 修改 OrderController 调用逻辑
@RestController
@RequestMapping("/order")
public class OrderController {
private final PriceService priceService;
public OrderController(PriceService priceService) {
this.priceService = priceService;
}
@GetMapping("/getPrice")
public BigDecimal getPrice(String productId) {
final BigDecimal price = priceService.getPrice(productId);
return price;
}
}
5)运行 OrderService 服务,访问 http://localhost:8005/order/getPrice?productId=123
,返回:
100
说明调用成功。