SpringCloud-聲明式Rest調用Feign
阿新 • • 發佈:2018-06-19
conf ron clas 相關 依賴庫 height .com urn tree
前言:一般情況下我們通常使用RestTemplate來實現聲明式遠程調用,但是當參數過多,那麽效率就會變得很低,並且難以維護,所以在微服務當中也有聲明式Rest調用的組件Feign
一、Feign簡介
Feign是Netflix開發的聲明式、模板化的http客戶端,Feign可以幫我們更加便捷、優雅地調用HTTP API。在SpringCloud中使用Feign非常簡單,創建一個接口,並在接口上加上註解,就完成了聲明式調用;
二、Feign與SpringCloud的整合簡單使用
註:本次學習記錄是基於之前的Eureka介紹和Ribbon介紹之上實踐,這裏只展示關鍵代碼,其余代碼可在代碼示例中查看;
1、創建基於Eureka和Ribbon的服務端和兩個客戶端生產者、消費者:
2、在消費者module中的maven依賴中添加相關依賴庫,創建Feign訪問接口,並註解,通過識別Eureka提供的應用名稱,來找對應的請求路徑:
pom.xml:
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-feign</artifactId> </dependency>
Feign接口:
import org.springframework.cloud.netflix.feign.FeignClient; import org.springframework.web.bind.annotation.RequestMapping; @FeignClient(name = "CLIENT-87") public interface UserFeign { @RequestMapping("/getUser") public String getUser(); }
Controller:
@Autowired private UserFeign userFeign; @RequestMapping("/getUser") public String getUser() { return userFeign.getUser(); }
在application.java啟動類中加入@EnableFeignClients註解。
3、分別啟動Server、Client生產者、Client消費者,並調用訪問http://localhost:8761、http://localhost:8762/getUser,如圖:
調用成功!
代碼示例:https://gitee.com/lfalex/springcloud-example( eureka-feign-client、 eureka-ribbon-server、 eureka-ribbon-client2這三個module)
SpringCloud-聲明式Rest調用Feign