javascript
Spring Cloud 入门 之 Feign 篇(三)
一、前言
在上一篇文章《Spring Cloud 入門 之 Ribbon 篇(二)》?中介紹了 Ribbon 使用負載均衡調用微服務,但存在一個問題:消費端每個請求方法中都需要拼接請求服務的 URL 地址,存在硬編碼問題且不符合面向對象編程思想。如果服務名稱發生變化,消費端也需要跟著修改。
本篇文章將介紹 Feign 來解決上邊的問題。
二、簡單介紹
Feign 是一個聲明式的 Web Service 客戶端。使用 Feign 能讓編寫 Web Service 客戶端更加簡單,同時支持與Eureka、Ribbon 組合使用以支持負載均衡。
Spring Cloud 對 Feign 進行了封裝,使其支持了 Spring MVC 標準注解和 HttpMessageConverters。
Feign 的使用方法是定義一個接口,然后在其上邊添加 @FeignClient 注解。
三、實戰演練
本次測試案例基于之前發表的文章中介紹的案例進行演示,不清楚的讀者請先轉移至?《Spring Cloud 入門 之 Ribbon 篇(二)》?進行瀏覽。
#?3.1 添加依賴
在 common-api 和 order-server 項目中添加依賴:
<!-- feign --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency>#?3.2 定義新接口
在 common-api 中項目中新建一個接口:
@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 類定義的方法一致。
#?3.3 修改調用
在 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 拼接問題,從而實現面向對象編程。
#?3.4 啟動 Feign 功能
在啟動類上添加?@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,也就實現了負載均衡的功能。
四、案例源碼
Feign demo 源碼
總結
以上是生活随笔為你收集整理的Spring Cloud 入门 之 Feign 篇(三)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: poj 1935(搜索+回溯)
- 下一篇: 网站为什么 JS 调用尽量放到网页底部?