日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

Spring Cloud 入门 之 Feign 篇(三)

發布時間:2025/3/16 javascript 24 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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 篇(三)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。