一、前言
在上一篇文章《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,也就實現了負載均衡的功能。
四、案例源碼
- 本文作者: MoonlightL
- 本文鏈接: https://www.extlight.com/2018/07/10/Spring-Cloud-入門-之-Feign-篇(三)/
- 版權聲明: 本博客所有文章除特別聲明外均爲原創,採用 CC BY-NC-SA 4.0 許可協議。轉載請在文章開頭明顯位置註明原文鏈接和作者等相關信息,明確指出修改(如有),並通過 E-mail 等方式告知,謝謝合作!