微服務遠端呼叫-Feign
存在下面的問題:
•程式碼可讀性差,程式設計體驗不統一
•引數複雜URL難以維護
Feign是一個宣告式的http客戶端,官方地址:https://github.com/OpenFeign/feign
其作用就是幫助我們優雅的實現http請求的傳送,解決上面提到的問題。
Fegin的使用步驟如下:
1)引入依賴
我們在order-service服務的pom檔案中引入feign的依賴:
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency>
2)添加註解
在order-service的啟動類添加註解開啟Feign的功能:@EnableFeignClients(import org.springframework.cloud.openfeign.EnableFeignClients;)
3)編寫Feign的客戶端
在order-service中新建一個介面,內容如下:
package cn.itcast.order.client;import cn.itcast.order.pojo.User; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; @FeignClient("user-service") public interface UserClient { @GetMapping("/user/{id}") User findById(@PathVariable("id") Long id); }
這個客戶端主要是基於SpringMVC的註解來宣告遠端呼叫的資訊,比如:
-
服務名稱:userservice
-
請求方式:GET
-
請求路徑:/user/{id}
-
請求引數:Long id
-
返回值型別:User
這樣,Feign就可以幫助我們傳送http請求,無需自己使用RestTemplate來發送了。
4)測試
修改order-service中的OrderService類中的queryOrderById方法,使用Feign客戶端代替RestTemplate:
是不是看起來優雅多了。
5)總結
使用Feign的步驟:
① 引入依賴
② 新增@EnableFeignClients註解
③ 編寫FeignClient介面,需要加 @FeignClient("user-service") 註解 ,裡面的 user-service 為要呼叫服務的應用名稱
④ 使用FeignClient中定義的方法代替 RestTemplate