1. 程式人生 > >Spring Cloud與微服務之Feign

Spring Cloud與微服務之Feign

文章目錄

Feign簡介

  Feign是Netflix開發的宣告式、模板化的HTTP客戶端,其靈感來自Retrofit、JAXRS-2.0以及WebSocket。Feign可以幫助我們更加便捷、優雅地呼叫HTTP API。

  在SpringCloud中,使用Feign非常簡單——建立一個介面,並在介面上新增一些註解,程式碼就完成了。Feign支援多種註解,例如Feign自帶的註解或者JAX-RS註解等。

  SpringCloud對Feign進行了增強,使Feign支援了SpringMVC註解,並整合了Ribbon和Eureka,從而讓Feign的使用更加的方便。

Feign的使用

這裡接前面的[Spring Cloud與微服務之訂單微服務]。(https://blog.csdn.net/ZZY1078689276/article/details/84982360)

  新增pom.xml依賴

    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-feign</artifactId>
    </dependency>

  新增自定義的Feign介面ItemFeignClient

package com.lyc.feign;

import com.lyc.item.entity.Item;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

@FeignClient(value = "springcloud-goods-item")    //宣告這是一個Feign的客戶端
public interface ItemFeignClient {

    @GetMapping("/item/{id}")
    public Item queryItemById(@PathVariable("id") Long id);

}

  最後在OrderApplication中啟用Feign

@EnableFeignClients

  使用的時候,直接使用Spring的@Autowired方法注入就可以了,比如說在ItemService中通過下面的方式來進行使用

@Autowired
private ItemFeignClient itemFeignClient;

Feign的使用分析

  當我們訪問下面的介面時

http://127.0.0.1:8082/order/13135351635

  訂單微服務會呼叫下面的方法:

this.itemFeignClient.queryItemById(id)

  而該方法是通過下面的方式注入的

@Autowired
private ItemFeignClient itemFeignClient;

  在ItemFeignClient中,我們指定了訂單微服務將要請求的商品微服務的服務名稱springcloud-goods-item以及服務的請求方式介面:

@GetMapping("/item/{id}")
public Item queryItemById(@PathVariable("id") Long id);

  而Feign就是通過在Eureka中找到springcloud-goods-item所對應的商品微服務的服務項,然後開始請求商品微服務的商品條目資訊,例如可能會隨機訪問到下面的商品條目地址:

http://127.0.0.1:8081/item/1

  最後將查詢的結果直接返回到訂單微服務中。完成訂單微服務對於商品微服務中的商品條目的請求操作。