什麼是Feign?
Spring Cloud integrates Ribbon and Eureka to provide a load balanced http client when using Feign.
Spring Cloud使用Feign時,集成了Ribbon和Eureka, 以提供實現負載平衡的http客戶端。
Feign測試
上一節我們使用RestTemplate實現服務調用,這一節使用Feign。
修改sales-order-service
- 增加Maven依賴:
<code>
<dependency>
\t<groupid>org.springframework.cloud/<groupid>
\t <artifactid>spring-cloud-starter-openfeign/<artifactid>
/<dependency>/<code>
- 定義ProductClient接口
接口的路徑、參數和返回值要與ProductController一致。
<code>@FeignClient(value = "sales-product-service")
public interface ProductClient {
@GetMapping("/product/get/{id}")
CommonResult<product> getById(@PathVariable("id")Long id);
}/<product>/<code>
- 修改OrderController
注入ProductClient
<code>@Autowired
ProductClient productClient;/<code>
修改原來RestTemplate方式的調用
<code>// feign
CommonResult<product> commonResult = productClient.getById(item.getProductId());
item.setProduct(commonResult.getData());/<product>/<code>
- 啟動類增加@EnableFeignClients註解
測試
結果與上一節的結果一致。
總結
程序啟動後,spring會掃描所有@FeignCleint註解的接口,並生成接口代理對象。
當接口的方法被調用,Feign從Eureka Server獲取到服務列表,並根據負載均衡算法實現服務調用。
![Spring Cloud快速入門(4),聲明式Rest客戶端:Feign](http://p2.ttnews.xyz/loading.gif)
閱讀更多 編碼筆記 的文章