原文地址:Spring Cloud 入門 之 Feign 篇(三)
博客地址:http://www.extlight.comjava
在上一篇文章《Spring Cloud 入門 之 Ribbon 篇(二)》 中介紹了 Ribbon 使用負載均衡調用微服務,但存在一個問題:消費端每一個請求方法中都須要拼接請求服務的 URL 地址,存在硬編碼問題且不符合面向對象編程思想。若是服務名稱發生變化,消費端也須要跟着修改。git
本篇文章將介紹 Feign 來解決上邊的問題。github
Feign 是一個聲明式的 Web Service 客戶端。使用 Feign 能讓編寫 Web Service 客戶端更加簡單,同時支持與Eureka、Ribbon 組合使用以支持負載均衡。spring
Spring Cloud 對 Feign 進行了封裝,使其支持了 Spring MVC 標準註解和 HttpMessageConverters。編程
Feign 的使用方法是定義一個接口,而後在其上邊添加 @FeignClient 註解。api
本次測試案例基於以前發表的文章中介紹的案例進行演示,不清楚的讀者請先轉移至 《Spring Cloud 入門 之 Ribbon 篇(二)》 進行瀏覽。app
在 common-api 和 order-server 項目中添加依賴:負載均衡
<!-- feign --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency>
在 common-api 中項目中新建一個接口:ide
@FeignClient(value="GOODS") public interface GoodsServiceClient { @RequestMapping("/goods/goodsInfo/{goodsId}") public Result goodsInfo(@PathVariable("goodsId") String goodsId); }
使用 @FeignClient 註解指定調用的微服務名稱,封裝了調用 USER-API 的過程,做爲消費方調用模板。微服務
注意:Feign 接口的定義最好與對外開發的 controller 中的方法定義一致,此處的定義與 goods-server 項目中 controller 類定義的方法一致。
在 order-server 項目中,使用 GoodsServiceClient 獲取商品信息:
@Service public class OrderServiceImpl implements OrderService{ // @Autowired // private RestTemplate restTemplate; @Autowired private GoodsServiceClient goodsServiceClient; @Override public void placeOrder(Order order) throws Exception{ //Result result = this.restTemplate.getForObject("http://GOODS/goods/goodsInfo/" + order.getGoodsId(), Result.class); Result result = this.goodsServiceClient.goodsInfo(order.getGoodsId()); if (result != null && result.getCode() == 200) { System.out.println("=====下訂單===="); System.out.println(result.getData()); } } }
直接使用 Feign 封裝模板調用服務方,免去麻煩的 URL 拼接問題,從而實現面向對象編程。
在啓動類上添加 @EnableEeignClients 註解:
@EnableFeignClients(basePackages = {"com.extlight.springcloud"}) @EnableEurekaClient @SpringBootApplication public class OrderServerApplication { public static void main(String[] args) { SpringApplication.run(OrderServerApplication.class, args); } }
因爲 order-server 項目中引用了 common-api 中的 GoodsServiceClient,不一樣屬一個項目,爲了實例化對象,所以須要在 @EnableFeignClients 註解中添加須要掃描的包路徑。
使用 Postman 請求訂單系統,請求結果以下圖:
請求成功,因爲 Feign 封裝了 Ribbon,也就實現了負載均衡的功能。