前言
閱讀之前先閱讀
https://blog.csdn.net/dtttyc/article/details/88853525
Feign 是什麼
Feign是web服務的客戶端,只需要創建接口,只需要添加接口,然後在接口上添加註解,簡單方便
爲什麼要使用Feign
- 不需要拼接URl和參數,之前的操作
@RequestMapping(value = "consumer/dept/get/{id}")
public Dept get(@PathVariable("id")Long id) {
return restTemplate.getForObject(REST_URL_PREFIX+"/dept/get/"+id,Dept.class);
}
- 支持springmvc註解,並且整合Eureka和Ribbon
- 封裝了http調用請求,更適合面試接口化的編程(動態代理實現)
Feign如何使用
- 引入pom文件
<!--Feign相關-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
- 創建接口,在接口上使用@FeignClient(value=“服務名稱”),需要注意的是他不可以是使用@GetMapping , 一般是在api端服務上
@FeignClient(value = "MICROSERVICECLOUD-DEPT")
public interface DeptClientService {
@RequestMapping(value = "dept/get/{id}",method = RequestMethod.GET)
Dept get(@PathVariable("id")long id);
- 在入口程序添加,使用註解 @EnableFeignClients和@ComponentScan
@EnableFeignClients(basePackages = {"com.atguigu.springcloud"})
@ComponentScan("com.atguigu.springcloud")
- 注入api,實現api
@Autowired
private DeptClientService deptClientService;
@RequestMapping(value = "/consumer/dept/get/{id}",method = RequestMethod.GET)
Dept get(@PathVariable("id")long id){
return this.deptClientService.get(id);
}
ribbon與Feign的區別
- ribbon 是一個基於http和tcp客戶端的負載均衡
- feign是一個http客戶端
- 調用方式不同,Ribbon是通過@ribbonClient
@RibbonClient(name = "MICROSERVICECLOUD-DEPT",configuration = MySelfRule.class)
- Feign是通過@EnableFeignClients
@EnableFeignClients(basePackages = {"com.atguigu.springcloud"})
- Ribbon需要自己構建http請求 url, 然後通過RestTemplate發送
- Feign通過接口和註解的形式發送,底層是通過動態代理實現(暫時不深入講解)
Eureka->ribbon->Feign
首先看一下整體的流程圖