SpringCloud實戰五:Spring Cloud Feign 服務呼叫
阿新 • • 發佈:2018-12-17
本篇主要講解什麼是Feign,以及Feign入門實踐
Feign是一個宣告式的Web Service客戶端,整合了註解,所以使用起來比較方便,通過它呼叫HTTP請求訪問遠端服務,就像訪問本地方法一樣簡單開發者完全無感知
Feign原理:我們首先會新增@EnableFeignClients註解開啟對 FeignClient掃描載入處理,掃描後會注入到SpringIOC容器,當定義的feign介面方法被呼叫時,通過JDK代理的方式,生成具體的RequestTemplate,RequestTemplate生成Request,交給URLConnection處理,並結合LoadBalanceClient與Ribbon,以負載均衡的方式發起服務間的呼叫
1.Feign具有以下一些重要特性:
- 整合了Hystrix,支援fallback容錯降級
- 整合了Ribbon,直接請求的負載均衡
- 支援HTTP請求和響應的壓縮
- 使用OkHttp替換原生URLConnection,提高效率
2.建立專案,快速開始
本篇入門實踐不依賴註冊中心等其他元件,後面Feign的高階使用篇會整合註冊中心,本篇的主要目的是通過 FeignClient 指定呼叫URL的方式,查詢GitHub上的倉庫資訊
- 新建個maven工程,再新增Module,型別為Spring Initializr,也就是SpringBoot的專案,新增Feign的依賴
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency>
- 在啟動主類上新增@EnableFeignClients,啟用Feign
@EnableFeignClients
@SpringBootApplication
public class SimplefeignApplication {
public static void main(String[] args) {
SpringApplication.run(SimplefeignApplication.class, args);
}
}
- 先確定要訪問的GitHub api是否能查詢到資訊,在瀏覽器輸入該地址:https://api.github.com/search/repositories?q=spring-cloud ,查詢出有30024條與spring-cloud相關資料
- 接下來是關鍵的 FeignClient的使用了,新建一個介面類IIndexFeignService
//指定了url就會訪問該url地址,否則會把name引數當作服務名到註冊中心中查詢該名字服務,此時指定了url後可以隨意命名
@FeignClient(name = "search-github" , url = "https://api.github.com")
public interface IIndexFeignService {
@RequestMapping(value = "/search/repositories" , method = RequestMethod.GET)
String search(@RequestParam("q") String query);
}
- 新建一個 IndexController ,注入IIndexFeignService,訪問search方法
@RestController
public class IndexController {
@Autowired private IIndexFeignService feignService;
@RequestMapping(value = "/search" , method = RequestMethod.GET)
public String search(@RequestParam("query") String query){
return feignService.search(query);
}
}
啟動專案,訪問:http://localhost:8080/search?query=spring-cloud ,可以看到返回的total_count與上面直接輸入url地址是一樣的,ok,feign入門實踐大功告成
程式碼已上傳至碼雲,原始碼,專案使用的版本資訊如下:
- SpringBoot 2.0.6.RELEASE
- SpringCloud Finchley.SR2(非常新的版本)