SpringCloud-Feign (四)

前言

閱讀之前先閱讀
https://blog.csdn.net/dtttyc/article/details/88853525

Feign 是什麼

Feign是web服務的客戶端,只需要創建接口,只需要添加接口,然後在接口上添加註解,簡單方便

爲什麼要使用Feign

  1. 不需要拼接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);
    }
  1. 支持springmvc註解,並且整合Eureka和Ribbon
  2. 封裝了http調用請求,更適合面試接口化的編程(動態代理實現)

Feign如何使用

  1. 引入pom文件
    <!--Feign相關-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-feign</artifactId>
        </dependency>
  1. 創建接口,在接口上使用@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);

  1. 在入口程序添加,使用註解 @EnableFeignClients和@ComponentScan
@EnableFeignClients(basePackages = {"com.atguigu.springcloud"})
@ComponentScan("com.atguigu.springcloud")
  1. 注入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的區別

  1. ribbon 是一個基於http和tcp客戶端的負載均衡
  2. feign是一個http客戶端
  3. 調用方式不同,Ribbon是通過@ribbonClient
@RibbonClient(name = "MICROSERVICECLOUD-DEPT",configuration = MySelfRule.class)
  1. Feign是通過@EnableFeignClients
@EnableFeignClients(basePackages = {"com.atguigu.springcloud"})
  1. Ribbon需要自己構建http請求 url, 然後通過RestTemplate發送
  2. Feign通過接口和註解的形式發送,底層是通過動態代理實現(暫時不深入講解)

Eureka->ribbon->Feign

首先看一下整體的流程圖
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章