[toc]‘
1. 概述 - 伪RPC
Feign:
- 概念: 整合了Ribbon和Eureka来提供均衡负载的HTTP客户端实现 - 基于Ribbon实现
- 底层: Feign在RestTemplate的基础上对其封装,由它来帮助我们定义和实现依赖服务接口的定义。- 简化了Ribbon的使用
- 使用: 只需要定义服务绑定接口且以声明式的方法,优雅而简单的实现了服务调用
2. 使用
步骤1 - 添加依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
由下图可知:内部依赖Ribbon、Hystrix等等包
步骤2 - 服务消费者启动类添加@EnableFeignClient
@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
public class OrderServiceApplication {
public static void main(String[] args) {
SpringApplication.run(OrderServiceApplication.class, args);
}
}
步骤3 - 在消费者项目创建一个于服务者控制器完全一样的接口
FeignClient接口定义规则
// 服务者的应用名
@FeignClient(name="productService")
public interface ProductServiceClient {
@GetMapping(value = "products/{id}")
@ResponseBody
public Product queryById(@PathVariable("id") Integer id);
@RequestMapping(value = "products/", method = RequestMethod.GET)
@ResponseBody
public List<Product> listUI();
}
步骤4 - 消费者获取服务提供者的数据
@Controller
@RequestMapping("books")
public class BookController {
@Autowired
ProductServiceClient productServiceClient;
// 当浏览器访问 /books/testProducts地址时,该服务又访问另一个服务进行获取产品信息
@GetMapping("testProducts")
@ResponseBody
public List<Product> testFeign() {
return productServiceClient.listUI();
}
}